Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream over a List of Map and collect specific key

This is my List:

[
    {name: 'moe', age: 40}, 
    {name: 'larry', age: 50}, 
    {name: 'curly', age: 60}
];

I want to pluck name values and create another List like this:

["moe", "larry", "curly"]

I've written this code and it works:

List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}

But how to do it in using stream. I've tried this code which doesn't work.

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
like image 266
Snow Avatar asked Jun 06 '17 09:06

Snow


2 Answers

Since your List appears to be a List<Map<String,Object>, your stream pipeline would produce a List<Object>:

List<Object> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

Or you could cast the value to String if you are sure you are going to get only Strings:

List<String> newList = list.stream().map(x -> (String)x.get("name")).collect(Collectors.toList());
like image 131
Eran Avatar answered Oct 30 '22 22:10

Eran


x.get("name") should be cast to String.

for example:

List<String> newList = list.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());

like image 40
wanda Avatar answered Oct 30 '22 22:10

wanda