Java 8 find max

I use max()to find the maximum value in the list, but the code below returns 4, although the maximum value 90.

List<Integer> list = new ArrayList<>(Arrays.asList(4,12,19,10,90,30,60,17,90));
System.out.println(list.stream().max(Integer::max).get());
+4
source share
2 answers

Stream#max(Comparator)takes value Comparator. You want to use Integer#compare(int, int)as a comparison function.

list.stream().max(Integer::compare).get()

You provided Integer#max(int, int)as an implementation Comparator#compare(int, int). This method does not meet the requirements Comparator#compare. Instead of returning a value indicating that it is the largest, it returns the value of the largest.

+11
source

You need to call the map on intStream

System.out.println(list.stream().mapToInt(Integer::intValue).max().getAsInt());

i.e. 4

+3

Source: https://habr.com/ru/post/1568354/


All Articles