假设我有一个人物对象,其中包含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;
但是如果我想在不使用索引的情况下访问每个人的name
属性呢?例如,要创建一个只是名称或头发颜色的数组或列表?我是否必须手动迭代people
数组?或者像String[] peopleNames = people.name
这样的Java有什么很酷的东西吗?
答案 0 :(得分:4)
java 8:
String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
答案 1 :(得分: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.