7

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());
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Snow
  • 71
  • 1
  • 3

3 Answers3

10

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());
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    this looks like `json` and there are ways to convert that to `String` instead of that `Object`... I would suggest that also – Eugene Jun 06 '17 at 10:01
2

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

for example:

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

wanda
  • 21
  • 1
1

If list from your iterator has type of Map<String, Object> then I think that the best way to do that task is just invoke method keySet() which will return Set but you can create ArrayList from it in the following way:

List<String> result = new ArrayList(list.keySet());
Holger
  • 285,553
  • 42
  • 434
  • 765
Alex
  • 1,940
  • 2
  • 18
  • 36