Get list of attributes of an object in an List

前端 未结 8 1719
青春惊慌失措
青春惊慌失措 2020-12-12 19:12

When there is an List, is there a possibility of getting List of all person.getName() out of that? Is there an prepared call for that

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 19:27

    Java 8 and above:

    List namesList = personList.stream()
                                       .map(Person::getName)
                                       .collect(Collectors.toList());
    

    If you need to make sure you get an ArrayList as a result, you have to change the last line to:

                                        ...
                                        .collect(Collectors.toCollection(ArrayList::new));
    

    Java 7 and below:

    The standard collection API prior to Java 8 has no support for such transformation. You'll have to write a loop (or wrap it in some "map" function of your own), unless you turn to some fancier collection API / extension.

    (The lines in your Java snippet are exactly the lines I would use.)

    In Apache Commons, you could use CollectionUtils.collect and a Transformer

    In Guava, you could use the Lists.transform method.

提交回复
热议问题