How to make a new list with a property of an Map which is in another list

Rishikesh Chaudhari :

Imagine that I have a List<Map<String,Object>>:

[{'id':1,'name':'xyz'},{'id':2,'name':'abc'},{'id':3,'name':'pqr'}]

And I need to generate another list including the name in the above list:

List<String>

Avoiding using a loop, is it possible to achieve this by using java stream api?

Andrew Tobilko :
List<String> names = list.stream()
                         .map(i -> i.get("name").toString())
                         .collect(Collectors.toList());

Since i.get("name").toString() might produce a NPE, it's smart to filter out maps that don't contain the key "name":

List<String> names = list.stream()
                         .filter(i -> i.containsKey("name"))
                         .map(i -> i.get("name").toString())
                         .collect(Collectors.toList());

or

List<String> names = list.stream()
                         .map(i -> i.get("name"))
                         .filter(Objects::nonNull)
                         .map(Object::toString)
                         .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115149&siteId=1