How to convert List<Object> to Map<String, Map<String,List<Object>>>

  • A+
Category:Languages

convert List<Object> to Map<String, Map<String,List<Object>>>

I have List<Person> where Person is as below.

Person {

String personId;
LocalDate date;
String type;

//getters &amp; setters

}

I'm trying to convert this to List<Person> to Map<String, Map<LocalDate,List<Person>>> where outer map's key is personId and inner map's key is date and I couldn't figure out how to achieve this. Thus far have tried something like below. Open to Java 8 solutions as well.


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
)));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: