java - List<Object> 到 Map<String, Map<String,List<Object>>>

标签 java list collections java-8 hashmap

我有 List<Person>其中 Person如下所示。

class Person {

    String personId;
    LocalDate date;
    String type;

    // getters & setters

}

我正在尝试将其转换为 List<Person>Map<String, Map<LocalDate,List<Person>>>外部 map 的键是 personId内部 map 的关键是date我不知道如何实现这一目标。 到目前为止,已经尝试过类似下面的方法。也对 Java 8 解决方案开放。

Map<String,Map<LocalDate,List<Person>>> outerMap = new HashMap<>();
Map<LocalDate,List<Person>> innerMap = new HashMap<>();

for(Person p : list) {
    List<Person> innerList = new ArrayList<>();
    innerList.add(p);
    innerMap.put(p.getDate(), innerList);
    outerMap.put(p.getPersonId(), innerMap);
}

最佳答案

list.stream()
    .collect(Collectors.groupingBy(
        Person::getPersonId,
        Collectors.groupingBy(
            Person::getDate
)));

关于java - List<Object> 到 Map<String, Map<String,List<Object>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799555/

相关文章:

java - 使用java在mongodb中自动递增序列

python - 如何访问字典 python 中列表中的元素?

python - 交换列表中的两个元素显示意外行为

c# - myCollection.Add() 与 myCollection ["key"的性能]

c# - WPF - 绑定(bind)到对象中的集合

collections - 为什么 Meteor 提示集合的插入方法已经定义?

java - 找到 Recamán 序列的第 n 个值

java - 如何使用 spymemcached 动态添加 memcached 节点

java - 在没有 PowerMockito 的情况下在 java 中模拟 URL 对象

r - 使用 R Lapply 和函数参数列表迭代函数