Java 使用 lambda 将 Map 格式化为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30237577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using lambda to format Map into String
提问by TEXHIK
I have a map with Integer
keys and values. I need to transform it into a String
with this specific format: key1 - val1, key2 - val2, key3 - val3
. Now, I'm using forEach
to format each element, collect them into a List, and then do String.join();
我有一个带有Integer
键和值的地图。我需要将它转换为String
具有这种特定格式的:key1 - val1, key2 - val2, key3 - val3
. 现在,我使用forEach
格式化每个元素,将它们收集到一个列表中,然后执行 String.join();
List<String> ships = new ArrayList<>(4);
for (Map.Entry<Integer, Integer> entry : damagedMap.entrySet())
{
ships.add(entry.getKey() + " - " + entry.getValue());
}
result = String.join(",", ships);
Is there any shorter way to do it? And it would be good to do it with lambda, because I need some practice using lambdas.
有没有更短的方法来做到这一点?用 lambda 来做这件事会很好,因为我需要一些使用 lambda 的练习。
采纳答案by Jon Skeet
I think you're looking for something like this:
我想你正在寻找这样的东西:
import java.util.*;
import java.util.stream.*;
public class Test {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "foo");
map.put(2, "bar");
map.put(3, "baz");
String result = map.entrySet()
.stream()
.map(entry -> entry.getKey() + " - " + entry.getValue())
.collect(Collectors.joining(", "));
System.out.println(result);
}
}
To go through the bits in turn:
依次浏览这些位:
entrySet()
gets an iterable sequence of entriesstream()
creates a stream for that iterablemap()
converts that stream of entries into a stream of strings of the form "key - value"collect(Collectors.joining(", "))
joins all the entries in the stream into a single string, using", "
as the separator.Collectors.joining
is a method which returns aCollector
which can work on an input sequence of strings, giving a result of a single string.
entrySet()
获取一个可迭代的条目序列stream()
为该可迭代对象创建一个流map()
将该条目流转换为“键-值”形式的字符串流collect(Collectors.joining(", "))
将流中的所有条目连接成一个字符串,", "
用作分隔符。Collectors.joining
是一种返回 a 的方法,Collector
它可以处理输入的字符串序列,给出单个字符串的结果。
Note that the order is notguaranteed here, because HashMap
isn't ordered. You might want to use TreeMap
to get the values in key order.
请注意,这里不保证顺序,因为HashMap
不是有序的。您可能希望使用TreeMap
来按键顺序获取值。