连接List中所有Maps的String值 [英] Concatenate the String values of all Maps in a List

查看:125
本文介绍了连接List中所有Maps的String值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调整Lambda功能,但是在这里和那里很少有人挣扎。

I am trying to adapt Lambda features, however few struggles here and there.

List<Map<String, String>> list = new LinkedList<>();
Map<String, String> map = new HashMap<>();
map.put("data1", "12345");
map.put("data2", "45678");
list.add(map);

我只想以逗号分隔格式打印值,如 12345,45678

I just want to print the values in comma separated format like 12345,45678

所以这是我的试用

list.stream().map(Map::values).collect(Collectors.toList()) //Collectors.joining(",")

,输出为 [[12345,45678]] 。这意味着,有一个列表和内部列表,它在 0 索引处创建逗号分隔值。我确实理解它为什么会这样做。

and the output is [[12345,45678]]. It means, there's a list and inside list it's creating the comma separated value at 0 index. I do understand why it's doing though.

但我没有通过如何提取我想要的结果,除非我调用 .get(0) 在该表达式的末尾。

But I didn't get through how to extract my desired result unless I call .get(0) in the end of that expression.

任何有关如何更好地使用lambdas的帮助/更多见解将会有所帮助

Any help/some more insights on how to use lambdas better will be helpful

推荐答案

试试这个:

list.stream().map(Map::values).flatMap(Collection::stream).collect(Collectors.joining(","))

flatMap 方法将集合< Stream< String>> 展平为一个单个流< String>

The flatMap method flattens out a Collection<Stream<String>> into a single Stream<String>.

或者,您可以尝试@Holger在评论中建议的内容。

Alternately, you can try what @Holger suggested in the comments.

请注意,由于您使用的是 Map ,因此无法保证订单会被保留。您可能会在最后看到输出为 45678,12345 。如果您希望保留订单,可以使用 LinkedHashMap 而不是 HashMap

Note that since you are using a Map, there is no guarantee that the order will be preserved. You might see the output as 45678,12345 at your end. If you wish to preserve the order, you can use a LinkedHashMap instead of a HashMap.

这篇关于连接List中所有Maps的String值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆