Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 262
Ram Avatar asked Apr 12 '18 14:04

Ram


People also ask

How do I convert a list of strings to a list of objects?

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 .

What is list map in Java?

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


2 Answers

list.stream()
    .collect(Collectors.groupingBy(
        Person::getPersonId,
        Collectors.groupingBy(
            Person::getDate
)));
like image 55
Eugene Avatar answered Sep 21 '22 09:09

Eugene


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.

like image 21
fps Avatar answered Sep 21 '22 09:09

fps