获取List中对象的属性列表

Son*_*hut 39 java collections class list

什么时候有List<Person>可能获得所有的List person.getName()?有没有准备好的调用,或者我必须写一个foreach循环,如:

List<Person> personList = new ArrayList<Person>();
List<String> namesList = new ArrayList<String>();
for(Person person : personList){
    namesList.add(personList.getName());
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 81

Java 8及以上版本:

List<String> namesList = personList.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

如果您需要确保获得ArrayList结果,则必须将最后一行更改为:

                                    ...
                                    .collect(Collectors.toCollection(ArrayList::new));
Run Code Online (Sandbox Code Playgroud)

Java 7及以下版本:

Java 8之前的标准集合API不支持此类转换.你必须编写一个循环(或将它包装在你自己的某个"map"函数中),除非你转向一些更高级的集合API /扩展.

(Java片段中的行正好是我要使用的行.)

在Apache Commons中,您可以使用CollectionUtils.collect和aTransformer

在Guava中,您可以使用该Lists.transform方法.


小智 10

你可能已经这样做了,但对其他人来说

使用Java 1.8

List<String> namesList = personList.stream().map(p -> p.getName()).collect(Collectors.toList()); 
Run Code Online (Sandbox Code Playgroud)


Sur*_*dip 6

试试这个

Collection<String> names = CollectionUtils.collect(personList, TransformerUtils.invokerTransformer("getName"));  
Run Code Online (Sandbox Code Playgroud)

使用apache commons collection api.