Java-从列表/数组中的每个对象获取单个属性的最简单方法? [英] Java - Easiest way to get single property from each object in a list/array?

查看:138
本文介绍了Java-从列表/数组中的每个对象获取单个属性的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have a person object with properties such as name, hair color, and eye color. I have the following array Person[] people that contains instances of person objects.

我知道我可以使用

// 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这样的好东西?

But what if I want to access the name property of everyone without using indexes? For example, to create an array or list of just names or hair color? Do I have to manually iterate through my people array? Or is there something cool in Java like String[] peopleNames = people.name?

推荐答案

两个选项:

  1. 迭代
  2. 流( Java 8 )

迭代

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

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

这篇关于Java-从列表/数组中的每个对象获取单个属性的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆