假设我有一个 person 对象,其属性如下name
, hair color
, and eye color
。我有以下数组Person[] people
包含 person 对象的实例。
我知道我可以得到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;
但是如果我想访问name
不使用索引的情况下每个人的财产?例如,创建一个仅包含名称或头发颜色的数组或列表?我是否必须手动迭代我的people
大批?或者Java中有一些很酷的东西,比如String[] peopleNames = people.name
?
两种选择:
- 迭代
- 流(Java 8)
迭代
List<String> names = new ArrayList<>();
for (Person p : people) {
names.add(p.name);
}
Streams
String[] names = Arrays.stream(people).map(p -> p.name).toArray(size -> new String[people.length]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)