2015-07-13 25 views
34

Ho una lista di Integerlist e dal list.stream() voglio il valore massimo. Qual è il modo più semplice? Ho bisogno di un comparatore?come trovare il valore massimo da un intero utilizzando lo stream in java 8?

+1

Leggi 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

Potresti avere i tuoi motivi per usare uno Stream, ma non dimenticare 'Collections. max' .. –

risposta

105

Si può o convertire il flusso di IntStream:

OptionalInt max = list.stream().mapToInt(Integer::intValue).max(); 

o specificare il comparatore ordine naturale:

Optional<Integer> max = list.stream().max(Comparator.naturalOrder()); 

Oppure utilizzare ridurre operazione:

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

Oppure utilizzare collector:

Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder())); 

o utilizzare IntSummaryStatistics:

int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax(); 
+5

Sarebbe interessante sapere quale è più efficiente. – Roland

+1

@Roland Voterò per il primo. –

+0

Posso chiedere perché, Tagir? – elect

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

Funziona solo se tutti i valori sono positivi. Utilizzare Integer.MIN_VALUE anziché 0 in reduce(). – rolika

3

Un'altra versione potrebbe essere:

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

codice corretto:

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

o

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

È possibile utilizzare int max = Stream.of (1,2,3,4,5) .reduce (0, (a, b) -> Math.max (a, b)); funziona sia per numeri positivi che negativi

+1

Non funziona per il negativo. – shmosel

Problemi correlati