说我有一个如属性的人的对象name,hair color和eye 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?
Java 8:
String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
Run Code Online (Sandbox Code Playgroud)
两种选择:
迭代
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)