Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate the String values of all Maps in a List

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);

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

So here goes my trial

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

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.

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

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

like image 746
RaceBase Avatar asked Jun 25 '15 17:06

RaceBase


1 Answers

Try this :

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

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

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

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.

like image 90
Chetan Kinger Avatar answered Oct 06 '22 08:10

Chetan Kinger