Skip to content

How to get maximum value from the Collection (for example ArrayList)?

To find the maximum value in a Java Collection (such as an ArrayList), you can use either the Collections.max() utility method or Java 8 Streams.

Using Collections.max() The Collections.max() method returns the greatest element of a collection according to the natural ordering of its elements. All elements must implement the Comparable interface.

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

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(5);
        numbers.add(20);
        numbers.add(15);

        Integer max = Collections.max(numbers);
        System.out.println("Maximum value: " + max); // Output: Maximum value: 20
    }
}

Using Java 8 Streams Alternatively, you can use Stream.max() with a Comparator. This approach is preferred when you need custom comparison logic or are working with objects that do not implement Comparable.

java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(5);
        numbers.add(20);
        numbers.add(15);

        Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder());
        max.ifPresent(value -> System.out.println("Maximum value: " + value));
    }
}

Important Notes:

  • Collections.max() throws NoSuchElementException if the collection is empty.
  • Stream.max() returns an Optional<Integer>, which safely handles empty collections without throwing exceptions.
  • For custom objects, pass a Comparator to both methods to define how values should be compared.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.