Java find max number in List with stream

Here are 3 ways to find the maximum number inside a list with lambda in Java:

import java.util.List;
import java.util.stream.Collectors;

public class MainFindBiggestNumber {

    public static void main(String[] args) {
        List<Integer> list = List.of(10, 5, -10, 21, 56, 32, 23);

        // Using reduce method
        Integer maxWithReduce = list.stream().reduce((x, y) -> Integer.max(x, y)).get();
        System.out.println("max number using reduce: " + maxWithReduce);

        // using max method
        Integer maxWithMax = list.stream().max(Integer::compareTo).get();
        System.out.println("max number with max: " + maxWithMax);

        // using collector
        Integer maxWithCollector = list.stream()
                .collect(Collectors.maxBy(Integer::compare)).get();
        System.out.println("max number with collector: " + maxWithCollector);
    }
}
max number using reduce: 56
max number with max: 56
max number with collector: 56

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.