本文介绍了如何转换Map< String,String>列出< String>使用谷歌收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含字符串的地图,我想将其转换为一个字符串列表,其中作为键值分隔符。是否可以使用谷歌收藏?
I have a map with strings, I want to transform it to a list of strings with " " as a key value separator. Is it possible using google collections?
我想用谷歌收藏品做的代码示例:
Code example that I want to do using google collections:
public static List<String> addLstOfSetEnvVariables(Map<String, String> env)
{
ArrayList<String> result = Lists.newArrayList();
for (Entry<String, String> entry : env.entrySet())
{
result.add(entry.getKey() + " " + entry.getValue());
}
return result;
}
推荐答案
在这里:
private static final Joiner JOINER = Joiner.on(' ');
public List<String> mapToList(final Map<String, String> input){
return Lists.newArrayList(
Iterables.transform(
input.entrySet(), new Function<Map.Entry<String, String>, String>(){
@Override
public String apply(final Map.Entry<String, String> input){
return JOINER.join(input.getKey(), input.getValue());
}
}));
}
更新:优化代码。使用Joiner常量应该比String.concat()快得多
Update: optimized code. Using a Joiner constant should be much faster than String.concat()
这些天,我当然会这样做Java 8流。不需要外部库。
These days, I would of course do this with Java 8 streams. No external lib needed.
public List<String> mapToList(final Map<String, String> input) {
return input.entrySet()
.stream()
.map(e -> new StringBuilder(
e.getKey().length()
+ e.getValue().length()
+ 1
).append(e.getKey())
.append(' ')
.append(e.getValue())
.toString()
)
.collect(Collectors.toList());
}
这篇关于如何转换Map< String,String>列出< String>使用谷歌收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!