how to find maximum value from a Integer using stream in java 8?

狂风中的少年 提交于 2019-12-03 18:22:01

问题


I have a list of Integer list and from the list.stream() I want the maximum value. What is the simplest way? Do I need comparator?


回答1:


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();



回答2:


int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));



回答3:


Another version could be:

int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();



回答4:


Correct code:

int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));

or

int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);



回答5:


With stream and reduce

Optional<Integer> max = list.stream().reduce(Math::max);



回答6:


You can also use below code snipped:

int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();

Another alternative:

list.sort(Comparator.reverseOrder()); // max value will come first
int max = list.get(0);  



回答7:


int value = list.stream().max(Integer::compareTo).get();
System.out.println("value  :"+value );



回答8:


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



来源:https://stackoverflow.com/questions/31378324/how-to-find-maximum-value-from-a-integer-using-stream-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!