Tengo una lista de Integer listy list.stream()quiero el valor máximo. ¿Cuál es la forma más sencilla? ¿Necesito un comparador?
                    
                        java-8
                                java-stream
                                
                    
                    
                        pcbabu
fuente
                
                fuente

Collections.max...Respuestas:
Puede convertir la transmisión a
IntStream:O especifique el comparador de orden natural:
O utilice la operación de reducción:
O use el colector:
O use IntSummaryStatistics:
int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();fuente
int, entoncesmapToInt(...).max().getAsInt()oreduce(...).get()las cadenas de métodosint max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));fuente
Otra versión podría ser:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();fuente
Código correcto:
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);fuente
Con corriente y reducir
fuente
Integer::maxpero eso es exactamente lo mismo).También puede utilizar el siguiente código recortado:
int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();Otra alternativa:
list.sort(Comparator.reverseOrder()); // max value will come first int max = list.get(0);fuente
int value = list.stream().max(Integer::compareTo).get(); System.out.println("value :"+value );fuente
Puede usar int max = Stream.of (1,2,3,4,5) .reduce (0, (a, b) -> Math.max (a, b)); funciona tanto para números positivos como negativos
fuente
Integer.MIN_VALUEpara que funcione con números negativos.