不要收集到List
,只是为了提取一个值,当您可以首先收集最大元素时,例如
Map<String,Match> result =
Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
.collect(Collectors.groupingBy(Match::getType, Collectors.collectingAndThen(
Collectors.reducing(BinaryOperator.maxBy(
Comparator.comparingInt(Match::getScore))),
Optional::get)));
但每当你遇到需要提取一个Optional
在这样的背景下groupingBy
,值得检查的是带有 merge 函数的 toMap` 是否可以给出更简单的结果:
Map<String,Match> result =
Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
.collect(Collectors.toMap(Match::getType, Function.identity(),
BinaryOperator.maxBy(Comparator.comparingInt(Match::getScore))));
一旦你拥有了Map
你可以通过以下方式产生你想要的输出
result.values().forEach(m -> System.out.println(m.getType() + ": " + m.getScore()));
但如果你不需要实际的Match
实例,你可以做得更简单:
Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
.collect(Collectors.toMap(Match::getType, Match::getScore, Math::max))
.forEach((type,score) -> System.out.println(type + ": " + score));