I'm trying to convert a 3 level nested list into Nested HashMap.
The function declaration for the same is:
Map<Key1, Map<Key2, List<String>>> transformToMap (List<Obj1> inputList)
The inputList internally has nested list which again has nested list.
The code I've wrote is using traditional for loop as follow:
private Map<Key1 , Map<Key2, List<String>>> reverseLookup(List<Key2> key2List){
Map<Key1 , Map<Key2, List<String>>> resultMap = new HashMap<>();
key2List.forEach(key2->{
List<ElementObject> elementObjects = key2.getElementObjects();
elementObjects.forEach(elementObject->{
final String name = elementObject.getName();
elementObject.getApplicablePeriods().forEach(applicablePeriod-> {
Key1 key1 = applicablePeriod.getKey1();
Map<Key2, List<String>> map2 = resultMap.get(key1);
if(map2 == null){
map2 = new HashMap<>();
}
List<String> stringList = map2.get(key2);
if(stringList == null){
stringList = new ArrayList<>();
}
stringList.add(name);
map2.put(key2, stringList);
resultMap.put(key1, map2);
});
});
});
return resultMap;
}
The class structure for the same is as follow:
class Key2{
List<ElementObject> elementObjects;
//getters & setters
}
class ElementObject {
String name;
//few more params
List<ApplicablePeriod> applicablePeriods;
//getters & setters
}
class ApplicablePeriod{
Key1 key1;
//getters & setters
}
class Key1{
//some parameters
//getters & setters
}
The above code is fulfilling my expectations.
What will be the efficient way to transform it into stream lambda using Collectors.toMap ?
I've tried something as follow:
inputList
.stream()
.flatMap(item -> item.getObj2List().stream())
.flatMap(nestedItem -> nestedItem.getKeyList().stream())
.collect(Collectors.toMap(a-> a.get()))
But not getting what should be the next step in Collectors.toMap.
Not able to handle final String name = nestedItem.getName(); which is used just before 3rd for loop.
Let me know the way to solve this.