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
  • 27,221
  • 105
  • 339
  • 599
adam.kubi
  • 1,753
  • 3
  • 13
  • 14

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
  • 274,122
  • 60
  • 696
  • 724
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
  • 15,233
  • 5
  • 34
  • 34