Skip to content
Home » How to Find the Maximum Value from a Collection in Java

How to Find the Maximum Value from a Collection in Java

road sign with speed limit number in town

Here’s how to find the maximum value from a Collection in Java.

import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;

public class MaximumValueFromCollections {

    public static void main(String[] args) {
        System.out.println(max(List.of(6, 3, 1, 8, 3, 9, 2, 7)));
    }

    private static Integer max(Collection<Integer> collection) {
        return collection.stream()
                         .max(Integer::compareTo)
                         .orElseThrow(NoSuchElementException::new);
    }
}

If you have any questions, leave a comment or ask me on my social media.