There are many ways to find the max and min values of a List in Java. We will explore the following:
Finding the maximum and minimum values of a List using the max() and min() methods from the Collections class
To return the maximum element of the given collection, we can use the max() method, and to return the minimum value, we can use the min() method of the Collections class from the java.util package.
public class Test { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(7, 19, 14, 1, 12, 22, 18, 3, 28, 5)); System.out.println("Maximum value: " + Collections.max(list)); System.out.println("Minimum value: " + Collections.min(list)); } }
Output: Maximum value: 28 Minimum value: 1
Finding the maximum and minimum values in List using the Java 8 Streams
We can use the min() and max() Stream operations that accept the Comparator to return the largest and smallest numbers from the list.
public class Test { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(7, 19, 14, 1, 12, 22, 18, 3, 28, 5)); System.out.println("Maximum value: " + list.stream().max(Integer::compare).get()); System.out.println("Minimum value: " + list.stream().min(Integer::compare).get()); } }
Output: Maximum value: 28 Minimum value: 1
Here, we called the get() method because both max() and min() methods return the Optional.
Finding the Largest and Smallest Numbers in List Using Iteration
We can find the max and min values using the for loop like in the following example:
public class Test { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(7, 19, 14, 1, 12, 22, 18, 3, 28, 5)); System.out.println("Maximum value: " + getMax(list)); System.out.println("Minimum value: " + getMin(list)); } private static int getMax(List<Integer> numbers) { int maximum = -1; for (Integer number : numbers) { if (number > maximum) { maximum = number; } } return maximum; } private static int getMin(List<Integer> numbers) { int minimum = Integer.MAX_VALUE; for (Integer number : numbers) { if (number < minimum) { minimum = number; } } return minimum; } }
Output: Maximum value: 28 Minimum value: 1
Happy coding!