【问题标题】:Grouping List of object to list of object of another type using List.stream使用 List.stream 将对象列表分组到另一种类型的对象列表
【发布时间】:2019-12-23 06:32:36
【问题描述】:

我有以下两个类:

public class Child {
    private String name;
    private int roll;
    private int age;
    private Date dob;

   . . . .
   getters and setters
   . . . . 
  }

public class Parent {
    private String name;
    private int age;

    private List<Child> children;
   . . . .
   getters and setters
   . . . . 
  }

现在我有一个List&lt;Child&gt; 作为输入。我想根据名称和年龄属性按列表分组,并使用List.stream() 生成List&lt;Parent&gt;。任何指针将不胜感激,并提前致谢。

编辑:

Parent 和Child 类之间的映射将是Parent.name 等于Child.name 和Parent.age 等于Child.age(用于分组的属性);

【问题讨论】:

  • 您将如何生成Parents?你怎么知道给定Child 实例的Parent?
  • 我创建了Parent 类作为List&lt;Child&gt; 分组结果的容器。
  • 看着一个孩子,我怎么知道他的父母是谁?
  • 我发现在编辑后的情况下输入不完整。输入是孩子的列表,要找到孩子的父母,没有父母输入来比较 parent.name.equals(child.name)。总之,根据问题中的信息,无法获得所需的输出……要获得所需的输出,父子关系逻辑必须单独存储在子类中,不应该依赖于父对象。跨度>

标签: java stream java-stream


【解决方案1】:

您可以通过两个groupingBy 收集器获得Map&lt;String, Map&lt;Integer, List&lt;Child&gt;&gt;&gt;:

Map<String, Map<Integer, List<Parent>>> grouped = 
    input.stream()
         .collect(Collectors.groupingBy(Child::getName,
                                        Collectors.groupingBy(Child::getAge)));

这个Map 可用于生成Parent 实例:

List<Parent> parents = 
    grouped.entrySet()
           .stream()
           .flatMap(e1 -> e1.getValue()
                            .entrySet()
                            .stream()
                            .map(e2 -> new Parent(e1.getKey(),e2.getKey(),e2.getValue())))
           .collect(Collectors.toList());

假设存在一个接受姓名、年龄和List&lt;Child&gt; 的Parent 构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多