Geo*_*iev 3 java lambda hashmap java-8
我试图将以下代码的输出保存在名为"output"的字符串变量中.但是,我得到这个编译错误"在封闭范围内定义的局部变量输出必须是最终的或有效的最终".我确实尝试将输出变量声明为final但我得到另一个编译错误"无法分配最终的局部变量输出.它必须是空白而不是使用复合赋值"任何建议,好吗?
String output = "";
map.entrySet().stream().sorted(
Map.Entry.<String, Integer> comparingByValue()
.reversed()
.thenComparing(Map.Entry.comparingByKey()))
.forEach(entry -> {
output += entry.getKey() + " - " + entry.getValue();
});
Run Code Online (Sandbox Code Playgroud)
有一个收藏家:joining().
String output = map.entrySet().stream()
.sorted(Map.Entry.<String, Integer> comparingByValue()
.reversed()
.thenComparing(Map.Entry.comparingByKey())
)
.map(entry -> entry.getKey() + " - " + entry.getValue())
.collect(joining());
Run Code Online (Sandbox Code Playgroud)
您还可以添加分隔符:joining(", ").