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

时间:2017-04-06 16:24:49

标签: 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;

但是如果我想在不使用索引的情况下访问每个人的name属性呢?例如,要创建一个只是名称或头发颜色的数组或列表?我是否必须手动迭代people数组?或者像String[] peopleNames = people.name这样的Java有什么很酷的东西吗?

3 个答案:

答案 0 :(得分:4)

java 8:

String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);

答案 1 :(得分:3)

两个选项:

  1. 迭代
  2. Streams( Java 8
  3. 迭代

    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]);
    

答案 2 :(得分:0)

You are seeking a functional feature in an initially imperative-only language Java. As already mentioned in other answers, since Java 8, you also have functional elements (e.g., streams). However, they are not yet recommended to be used. This blog post explains the disadvantages of streams over loops (i.e., performance, readability, maintainability).

If you are looking for functional and safe code without such major implications, try Scala:

case class Person(name: String)
val persons = Array(Person("george"), Person("michael"), Person("dexter"))
val personNames = persons.map(_.name)

The main difference is that this Scala code is simple to read and it is comparably performant as a Java code that uses a loop because the translated Scala-to-Java code uses a while loop internally.