Stream over a list of cards and collect a specific key

This is my list:

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

I want to wrest the values nameand create another one Listas follows:

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

I wrote 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 when using stream. I tried this code that does not work.

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
+6
source share
3 answers

Since yours Listlooks like List<Map<String,Object>, your stream pipeline will create List<Object>:

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

Or you can specify a value Stringif you are sure you will get only Strings:

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

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

eg:

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

+2
source

If listyour iterator has a type Map<String, Object>, then I think the best way to accomplish this task is to simply call a method keySet()that will return Set, but you can create ArrayListfrom it in the following way:

List<String> result = new ArrayList(list.keySet());
+1
source

All Articles