Constructing list from multi level map in Java 8
One method use Java 8 Stream and lambda function:
String format = "In class %s %s with roll number %d";
List<String> result = new ArrayList<>();
outerMap.entrySet().stream()
.forEach(v -> {
String className = v.getKey();
v.getValue().entrySet().stream()
.forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
});
You can simply use Map.forEach
for this operation as:
List<String> messages = new ArrayList<>();
outerMap.forEach((cls, students) ->
students.forEach((name, student) ->
messages.add(convertToMessage(cls, name, student.getRollNumber()))));
where convertToMessage
is a util as :
// this could be made cleaner using 'format'
String convertToMessage(String cls, String studentName, String rollNumber) {
return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
}
You may do it like so,
List<String> formattedOutput = outerMap
.entrySet().stream()
.flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
+ " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
.collect(Collectors.toList());
You have to use the flatMap
operator instead of map
operator.