rom58 rom58 - 6 months ago 17
Java Question

Java: Creating an Array from the Properties of Another Array

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?

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 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.

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

Answer

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

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