我有一個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. 如何在IntList中查找最大值?
- 6. 查找最小值和最大值JAVA
- 7. 在java中使用cassandra hector查找列的最大值。
- 8. Java:查找數組中的最大值
- 9. 在Java中查找num值和最小值/最大值值
- 10. 如何查找最大值
- 11. 如何在使用java的Excel工作表的列中查找最大值?
- 12. 如何在Java中使用數組查找最大數字?
- 13. 在hadoop中查找最大整數值(使用java編程)
- 14. 使用(java編程)在hadoop中查找最大整數值
- 15. 如何使用Java 8流?
- 16. 使用Java 8 Predicate查找「最」正確的值
- 17. 如何使用nCr查找最小值和最大值?
- 18. 如何使用OpenCV在圓圈中查找最大RGB值?
- 19. 使用循環查找python中的最大值和最小值
- 20. 使用Java流查找集合中的最小和最大數字
- 21. 如何使用python numpy在特定列中查找最大值和最小值?
- 22. 如何使用SQL查找表中的最大值?
- 23. 在Java中查找最小,最大和中間值
- 24. 使用Java查找最小和最大值
- 25. 如何正確查找Java-8中的流特徵?
- 26. 如何查找數組的最大值?
- 27. 如何查找列表框中的最大值和最小值
- 28. 在Java 8中查找列表的最大值,最小值,總和和平均值
- 29. 使用Spark java查找最大行數
- 30. 是FibonacciHeap最小堆?如何使用FibonacciHeap查找最大值?
閱讀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 .. .. –