I have a list of Integer values named list, and from the list.stream() I want the maximum value.
What is the simplest way? Do I need a comparator?
You may either convert the stream to IntStream:
OptionalInt max = list.stream().mapToInt(Integer::intValue).max(); Or specify the natural order comparator:
Optional<Integer> max = list.stream().max(Comparator.naturalOrder()); Or use reduce operation:
Optional<Integer> max = list.stream().reduce(Integer::max); Or use collector:
Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder())); Or use IntSummaryStatistics:
int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax(); int, then mapToInt(...).max().getAsInt() or reduce(...).get() to the method chainsint max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b)); int value = list.stream().max(Integer::compareTo).get(); System.out.println("value :"+value ); I think another easy way is
IntSummaryStatistics statistics = List.of(1, 2, 3).stream() .mapToInt(Integer::intValue) .summaryStatistics(); int max = statistics.getMax(); With this you can also getMin() amd other stuff like mean. A SummaryStatistics Object can be created from other Streams by supplying appropriate parameters.
With stream and reduce
Optional<Integer> max = list.stream().reduce(Math::max); Integer::max but that's exactly the same).you can also find the max element in a collection using bellow code:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); Optional<Integer> max = intList.stream().max((a, b) -> a - b); a - b is dangerous because of integer overflow → Arrays.asList(-2147483640, 100).stream().max((a, b) -> a - b) will result in Optional[-2147483640] but -2147483640 is not greater than 100In my case, need to convert a String (SeqNum) to integer and find a max value of it.
list.stream().map(TxnCharges::getSeqNum) .max(Comparator.comparingInt(s -> Integer.parseInt(s.trim()))) .orElse(null); list.stream().map(TxnCharges::getSeqNum).map(String::trim).mapToInt(Integer::parseInt).max().orElse(0) (but not applicable to List<Integer> as asked for)You could use int max= Stream.of(1,2,3,4,5).reduce(0,(a,b)->Math.max(a,b)); works for both positive and negative numbers
Integer.MIN_VALUE to make it work with negative numbers.
Collections.max..