2015-07-13 60 views
34

我有一個Integerlistlist.stream()的列表我想要的最大值。最簡單的方法是什麼?我需要比較器嗎?如何在Java 8中使用流的Integer查找最大值?

+1

閱讀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-- –

+9

您可能有理由使用Stream,但不要忘記'Collections。 max .. .. –

回答

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

會很有趣地知道哪一個更有效率。 – Roland

+1

@羅蘭我會爲第一個投票。 –

+0

請問爲什麼Tagir? – elect

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

相關問題