8

I am using max() to find the maximum value in the list but the code below returns 4 though the max value is 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());
Tiny
  • 26,031
  • 99
  • 315
  • 583
adam.kubi
  • 1,683
  • 2
  • 12
  • 13

2 Answers2

15

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

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

You were providing Integer#max(int, int) as an implementation of Comparator#compare(int, int). That method doesn't match the requirements of Comparator#compare. Instead of returning a value indicating which is biggest, it returns the value of the biggest.

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
3

You need to invoke map on intStream

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

Currently your code just returns the first value from the list i.e. 4 in your case

sol4me
  • 14,603
  • 5
  • 33
  • 32