【发布时间】:2021-12-27 18:43:05
【问题描述】:
我正在尝试做一些练习,但我不想使用 if 语句,因为程序会很长。我有一个列表人员,其中:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private Integer score;
private Group team;
private boolean active;
}
和
public enum Group {
G1, G2, G3
}
我的工作是找到一个人得分最高的组,但如果两个组的分数相同,我必须返回有更多不活跃人的组。如果inActive玩家的数量相同,我返回哪个组都没关系。
我在 Map 中对所有内容进行分组
Map<Group, List<Person>> collect = people.stream()
.collect(Collectors.groupingBy(Person::getTeam));
然后创建另外两个地图,我将分数和不活跃的人分组。
for (Map.Entry<Group, List<Person>> entry : collect.entrySet()) {
collect1.put(entry
.getKey(), entry.getValue().stream()
.mapToInt(Person::getScore).sum());
collect2.put(entry.getKey(), entry.getValue().stream()
.filter(p -> !p.isActive())
.count());
}
我现在如何比较以获得类似任务的结果。
【问题讨论】:
标签: java dictionary stream