示例Person类
class Person { String personId; LocalDate date; String type; // getters & setters }
1、使用stream()进行转换
list.stream() .collect(Collectors.groupingBy( Person::getPersonId, Collectors.groupingBy( Person::getDate )));
2、使用foreach实现转换
Map<String, Map<LocalDate, List<Person>>> outerMap = new HashMap<>(); list.forEach(p -> outerMap .computeIfAbsent(p.getPersonId(), k -> new HashMap<>()) // returns innerMap .computeIfAbsent(p.getDate(), k -> new ArrayList<>()) // returns innerList .add(p)); // adds Person to innerList
3、使用for循环转换
Map<String,Map<LocalDate,List<Person>>> outerMap = new HashMap<>(); for(Person p : list) { Map<LocalDate,List<Person>> innerMap = outerMap.get(p.getPersonId()); if (innerMap == null) { innerMap = new HashMap<>(); outerMap.put(p.getPersonId(), innerMap); } List<Person> innerList = innerMap.get(p.getDate()); if (innerList == null) { innerList = new ArrayList<>(); innerMap.put(p.getDate(), innerList); } innerList.add(p); }