Java-从列表/数组中的每个对象获取单个属性的最简单方法?

6 java arrays oop object

说我有一个如属性的人的对象namehair coloreye color。我有以下Person[] people包含个人对象实例的数组。

我知道我可以得到name一个Person对象的属性

// create a new instance of Person
Person george = new Person('george','brown','blue');
// <<< make a people array that contains the george instance here... >>>
// access the name property
String georgesName = people[0].name;
Run Code Online (Sandbox Code Playgroud)

但是,如果我想name不使用索引就访问所有人的财产怎么办?例如,要创建仅包含名称或头发颜色的数组或列表?我是否必须手动遍历people数组?还是Java中有什么很棒的东西String[] peopleNames = people.name

Zhe*_*yaM 5

Java 8:

String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
Run Code Online (Sandbox Code Playgroud)


m_c*_*ens 5

两种选择:

  1. 迭代
  2. 流(Java 8

迭代

List<String> names = new ArrayList<>();
for (Person p : people) {
    names.add(p.name);
}
Run Code Online (Sandbox Code Playgroud)

String[] names = Arrays.stream(people).map(p -> p.name).toArray(size -> new String[people.length]);
Run Code Online (Sandbox Code Playgroud)