Mam listę Integer listi od list.stream()Chcę maksymalną wartość. Jaki jest najprostszy sposób? Czy potrzebuję komparatora?
Collections.max...
Mam listę Integer listi od list.stream()Chcę maksymalną wartość. Jaki jest najprostszy sposób? Czy potrzebuję komparatora?
Collections.max...
Odpowiedzi:
Możesz przekonwertować strumień na IntStream:
OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
Lub określ naturalny komparator kolejności:
Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
Lub użyj zredukować operację:
Optional<Integer> max = list.stream().reduce(Integer::max);
Lub użyj kolektora:
Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
Lub użyj IntSummaryStatistics:
int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
int, to mapToInt(...).max().getAsInt()lub reduce(...).get()do łańcuchów metod
Inną wersją może być:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
Prawidłowy kod:
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
lub
int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
Ze strumieniem i zmniejsz
Optional<Integer> max = list.stream().reduce(Math::max);
Integer::maxale to dokładnie to samo).
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value :"+value );