get the max value from arrayList java and save it in int

h‮sptt‬://www.lautturi.com
get the max value from arrayList java and save it in int

To get the maximum value from an ArrayList of integers in Java and save it in an int variable, you can use the Collections.max() method from the Java Collections framework. Here's an example of how you could use this method:

import java.util.ArrayList;
import java.util.Collections;

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
int max = Collections.max(numbers);
System.out.println("The maximum value is: " + max);

This code will output "The maximum value is: 5".

Alternatively, you can use a for loop to iterate through the ArrayList and find the maximum value manually. Here's an example of how you could do this:

int max = Integer.MIN_VALUE;
for (int number : numbers) {
  if (number > max) {
    max = number;
  }
}
System.out.println("The maximum value is: " + max);

This code will also output "The maximum value is: 5".

Note that the Collections.max() method only works for ArrayLists of objects that implement the Comparable interface, such as Integer, Double, and String. If you are using a custom object, you will need to implement the Comparable interface and override the compareTo() method to specify how the objects should be compared.

Created Time:2017-11-01 12:04:59  Author:lautturi