【问题标题】:Convert List<Person> to Map<Integer, List<Integer>> using Lambdas使用 Lambda 将 List<Person> 转换为 Map<Integer, List<Integer>>
【发布时间】:2019-02-25 18:45:27
【问题描述】:

我想将列表转换为地图,如下所示。这是一个例子。

我有类似下面代码 sn-p 的学生列表。从中获取一个 Hasmap,其中 Key 为 Integer,即 Age,value 为 List。

从下面的输入提要中,我的回复应该如下所示。我如何做到这一点?

地图[[10, {1}], [20, {2,3,4}], [30,{5}]。 [40,{6}]];

private static List<Person> getPersonTestData() {
    List<Person> personList = new ArrayList<>();
    personList.add(Person.of(1, "First1", "Last1", 10));
    personList.add(Person.of(2, "First2", "Last2", 20));
    personList.add(Person.of(3, "First3", "Last3", 20));
    personList.add(Person.of(4, "First4", "Last4", 20));
    personList.add(Person.of(5, "First5", "Last5", 30));
    personList.add(Person.of(6, "First6", "Last6", 40));

    return personList;
}

提前谢谢......!

【问题讨论】:

    标签: java lambda java-8 java-stream


    【解决方案1】:

    您可以在下游使用 groupingBymapping 来做到这一点:

    Map<Integer, List<Integer>> ageToIdsMap = getPersonTestData().stream()
            .collect(Collectors.groupingBy(Person::getAge,
                    Collectors.mapping(Person::getId, Collectors.toList())));
    

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 1970-01-01
      • 2023-03-26
      • 2014-01-08
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多