Java:从另一个数组的属性创建一个数组 [英] Java: Creating an Array from the Properties of Another Array
问题描述
Java中是否有一种简单的方法(不涉及编写for循环)来从另一个不同对象数组的属性创建对象数组?
Is there a simple way in Java (that doesn't involve writing a for-loop) to create an array of objects from a property of another array of different objects?
例如,如果我有一个类型为 A
的对象数组,则定义为:
For example, if I have an array of objects of type A
, defined as:
public class A {
private String p;
public getP() {
return p;
}
}
我想创建一个字符串数组,其中包含每个 i
的 A [i] .p
值.
I want to create an array of Strings that contains the value of A[i].p
for each i
.
Essentially, I'm I want to do this: Creating an array from properties of objects in another array, but in Java.
我试图将 Arrays.copyOf(U [] original,int newLength,Class<?extended T []> newType)
连同lambda表达式一起使用,但这似乎并没有工作.我尝试过的:
I attempted to use Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType)
along with a lambda expression, but that didn't seem to work. What I tried:
Arrays.copyOf(arrayA, arrayA.length, (A a) -> a.getP());
推荐答案
在Java 8中,您可以使用 Stream
API,尤其是 map
函数:
With Java 8, you can use the Stream
API and particularly the map
function:
A[] as = { new A("foo"), new A("bar"), new A("blub") };
String[] ps = Stream.of(as).map(A::getP).toArray(String[]::new);
在这里, A :: getP
和 String [] :: new
是方法/构造函数引用.如果您没有想要的属性的合适方法,则还可以使用lambda函数:
Here, A::getP
and String[]::new
are method/constructor references. If you do not have a suitable method for the property you want to have, you could also use a lambda function:
String[] ps = Stream.of(as).map(a -> a.getP()).toArray(String[]::new);
这篇关于Java:从另一个数组的属性创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!