I have List<Person> where Person is as below.
class Person {
String personId;
LocalDate date;
String type;
// getters & 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);
}
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element).
list.stream()
.collect(Collectors.groupingBy(
Person::getPersonId,
Collectors.groupingBy(
Person::getDate
)));
This answer shows how to do it with streams and this other one how to do it with a traditional iterative approach. Here's yet another way:
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
This uses Map.computeIfAbsent to create a new innerMap and put it in the outerMap if not present (the key being personId), and also to create a new innerList and put it in the innerMap if not present (the key being date). Finally, the Person is added to the innerList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With