【问题标题】:Comparing elements in HasMap with List as a value将 HashMap 中的元素与 List 作为值进行比较
【发布时间】: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


    【解决方案1】:

    我不会将聚合存储在两个单独的地图中,而是使用对聚合结果进行分组的对象。类似的东西

    class GroupStats {
        private Group group;
        private int score;
        private int activePlayers;
    }
            
    

    为了简洁起见,我省略了构造函数和吸气剂。然后你可以做类似的事情

        collect.entrySet().stream().map(e -> {
            Group group = e.getKey();
            int score = e.getValue().stream()
                    .mapToInt(Person::getScore).sum();
            long activeCount = e.getValue().stream()
                    .filter(p -> p.isActive())
                    .count();
            return new GroupStats(group, score, activeCount);
        }).max(Comparator
                .comparingInt(GroupStats::getScore)
                .thenComparingLong(GroupStats::getActivePlayerCount))
        .ifPresent(stats -> System.out.println(stats.group));
    

    【讨论】:

    • 我正在考虑做这样的事情,但我无法添加任何新类,只是为了使用我所拥有的创建方法。
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多