java - 获取 List 中对象的属性列表

标签 java class list collections

当有 List<Person> , 是否有可能获得全部列表 person.getName()从那? 是否有为此准备好的调用,或者我是否必须编写一个 foreach 循环,例如:

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 作为结果,则必须将最后一行更改为:

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

Java 7 及以下版本:

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

(您的 Java 代码段中的行正是我将使用的行。)

在 Apache Commons 中,您可以使用 CollectionUtils.collectTransformer

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

关于java - 获取 List 中对象的属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309259/

相关文章:

java - 将 .c 转换为 .java

java - 访问来自不同类的变量

android - 抽屉导航 : text is hidden below actionbar?

c# - C# 中 Scala 的列表的协变和逆变 Monadic 类型

java - 如何在我的方法中将 MyClass.class 作为参数传递?

java - 如何用Java编写文件列表

c++ - 使用 NULL 值初始化静态函数数组

class - 拆分 UML 类图?

python-3.x - 使用列表理解中的错误处理将字符串转换为 float

python - 如何读取带有负步长的切片