我有一个多级地图,如下所示:
Map<String, Map<String, Student> outerMap =
{"cls1" : {"xyz" : Student(rollNumber=1, name="test1")},
"cls2" : {"abc" : Student(rollNumber=2, name="test2")}}
现在我想从上面的地图构造一个字符串列表,如下所示:
["In class cls1 xyz with roll number 1",
"In class cls2 abc with roll number 2"]
我写的内容如下,但这是行不通的,在这种情况下,我也浏览了这篇文章:Java 8 Streams - Nested Maps to List,但是并没有太多的想法。
List<String> classes = outerMap.keySet();
List<String> studentList = classes.stream()
.map(cls ->
outerMap.get(cls).keySet().stream()
.map(student -> "In class "+ cls +
student + " with roll number " +
outerMap.get(cls).get(student).getRollNum() +"\n"
).collect(Collectors.toList());
答案 0 :(得分:9)
您可以简单地使用Map.forEach
进行以下操作:
List<String> messages = new ArrayList<>();
outerMap.forEach((cls, students) ->
students.forEach((name, student) ->
messages.add(convertToMessage(cls, name, student.getRollNumber()))));
其中convertToMessage
是一个util,例如:
// this could be made cleaner using 'format'
String convertToMessage(String cls, String studentName, String rollNumber) {
return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
}
答案 1 :(得分:5)
您可以这样做
git reflog --date=relative
您必须使用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());
运算符而不是flatMap
运算符。
答案 2 :(得分:2)
一种方法使用Java 8 Stream和lambda函数:
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())));
});