获取List中对象的属性列表

获取List中对象的属性列表

本文介绍了获取List中对象的属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有列表< Person> ,是否有可能获得所有的列表person.getName()出于那个?
是否有准备好的电话,或者我必须写一个foreach循环,如:

When there is an List<Person>, is there a possibility of getting List of all person.getName() out of that?Is there an prepared call for that, or do I have to write an foreach loop like:

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


推荐答案

Java 8和上面:

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

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

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及以下版本:

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

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.

( Java代码段中的行正好是我要使用的行。)

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

在Apache Commons中,您可以使用和

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

在Guava中,您可以使用方法。

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

这篇关于获取List中对象的属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:25