如何转换Map< String,String>列出< String>使用谷歌收藏

编程入门 行业动态 更新时间:2024-10-10 09:15:53
本文介绍了如何转换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&lt; String,String&gt;列出&lt; String&gt;使用谷歌收藏

本文发布于:2023-11-12 13:01:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:收藏   amp   Map   lt   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!