我有一个Integer
list
和list.stream()
的列表我想要的最大值。最简单的方法是什么?我需要比较器吗?如何在Java 8中使用流的Integer查找最大值?
34
A
回答
105
您既可以将流转换为IntStream
:
OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
或指定的自然顺序比较:
Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
或者使用减少操作:
Optional<Integer> max = list.stream().reduce(Integer::max);
或者使用采集器:
个Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
或者使用IntSummaryStatistics:
int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
6
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
+5
只有所有的值都是正值,这才有效。在reduce()中使用Integer.MIN_VALUE而不是0。 – rolika
3
另一个版本可能是:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
1
正确的代码:
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
或
int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
-2
您可以使用int max = Stream.of(1,2,3,4,5).reduce(0,(a,b) - > Math.max(a,b)); 适用于正数和负数
+1
它不适用于否定。 – shmosel
相关问题
- 1. Java的8个流 - 查找最大嵌套列表
- 2. 如何使用vba在excel中查找组值的最大值?
- 3. 如何使用MySQL查找最大值
- 4. 查找最大值 - Java
- 5. 查找最小值和最大值JAVA
- 6. 如何在IntList中查找最大值?
- 7. 在java中使用cassandra hector查找列的最大值。
- 8. Java:查找数组中的最大值
- 9. 在Java中查找num值和最小值/最大值值
- 10. 如何在使用java的Excel工作表的列中查找最大值?
- 11. 使用(java编程)在hadoop中查找最大整数值
- 12. 在hadoop中查找最大整数值(使用java编程)
- 13. 如何在Java中使用数组查找最大数字?
- 14. 使用Java 8 Predicate查找“最”正确的值
- 15. 如何使用nCr查找最小值和最大值?
- 16. 如何使用OpenCV在圆圈中查找最大RGB值?
- 17. 使用Java流查找集合中的最小和最大数字
- 18. 如何使用SQL查找表中的最大值?
- 19. 在Java中查找最小,最大和中间值
- 20. 在Java 8中查找列表的最大值,最小值,总和和平均值
- 21. 如何查找列表框中的最大值和最小值
- 22. 使用Spark java查找最大行数
- 23. 简明的方式来获得Java 8流的最小值和最大值
- 24. 使用负数查找最大值
- 25. 在VBA中查找列的最大值
- 26. JAVA哈希表查找最大值
- 27. 在Java 8中使用流使用映射值的组
- 28. 使用模板查找最大值
- 29. 的Java 8嵌套流:在最后一个流返回值
- 30. 在java中查找最大数组
阅读javadoc:http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#max-java.util.Comparator - ,http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder-- –
您可能有理由使用Stream,但不要忘记'Collections。 max .. .. –