Java Programming Tutorials

Java programming tutorials with many code examples!

Java Collection min/max value


Having a Java Collection find min/max values? As in many cases it can easily be done with Java Collections API. See the following example…


The following Java code shows how to find min/max value in a Java Collection:


import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionsMinMax {

    // Orders bigger numbers before smaller
    static class ReverseComparator implements Comparator<Integer> {
        public int compare(Integer o1, Integer o2) {
            // Do it other way around:
            return o2 - o1;

    public static void main(String[] args) {
        List<Integer> scores = Arrays.asList(9, 2, 7, 8, 0, 3, 1);

        System.out.println("Scores: " + scores);

        System.out.println("Min score: " + Collections.min(scores));
        System.out.println("Max score: " + Collections.max(scores));

        Comparator<Integer> cmp = new ReverseComparator();
        System.out.println("Min score with own Comparator: "
                + Collections.min(scores, cmp));
        System.out.println("Max score with own Comparator: "
                + Collections.max(scores, cmp));

java.util.Collections has methods min and max that easily allow to find such values inside any Java Collection.

The second part shows how to use own Comparator for cases that we would like to compare instances of custom classes.

Here’s result of running the above Java code:

Scores: [9, 2, 7, 8, 0, 3, 1]
Min score: 0
Max score: 9
Min score with own Comparator: 9
Max score with own Comparator: 0

Easy as always with java.util.Collections. ;-)

Was it helpful? Share!