【问题标题】:java 8 - how to group by every element from the list [duplicate]java 8 - 如何按列表中的每个元素进行分组[重复]
【发布时间】:2020-09-06 10:06:14
【问题描述】:

我有 2 个列表:“组”和“人员”。最后,我想得到一张按每个“组”分组的地图。 由于最后一个 flatMap 方法,下面的代码无法编译,说“不能从静态上下文引用非静态方法”。

private static Map<Group, List<Person>> getAllGroupsOfSelectedPeople(List<Person> people) {
       List<Group> groups = getCurrentlyActiveGroups(people);
       return people.stream()
               .filter(p -> CollectionUtils.isNotEmpty(p.getSocials()))
               .filter(p -> p.getGroups().stream().anyMatch(groups::contains))
               .collect(Collectors.groupingBy(p -> p.getGroups().stream().flatMap(List::stream)));
   }

【问题讨论】:

  • 能分享一下 Group 和 Person 的主要方法吗?

标签: java collections java-stream


【解决方案1】:

flatMap 应该在collect 步骤之前使用,以生成所有GroupPerson 对。然后您可以将这些对分组。

private static Map<Group, List<Person>> getAllGroupsOfSelectedPeople(List<Person> people) {
       List<Group> groups = getCurrentlyActiveGroups(people);
       return people.stream()
               .filter(p -> CollectionUtils.isNotEmpty(p.getSocials()))
               .filter(p -> p.getGroups().stream().anyMatch(groups::contains))
               .flatMap(p -> p.getGroups()
                              .stream()
                              .map(g -> new SimpleEntry<Group,Person>(g,p)))
               .collect(Collectors.groupingBy(Map.Entry::getKey,
                                              Collectors.mapping(Map.Entry::getValue,
                                                                 Collectors.toList())));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2011-06-27
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多