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,都值得检查是否具有合并功能的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));


