Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Creating an Array from the Properties of Another Array

Tags:

java

arrays

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());
like image 563
rom58 Avatar asked Sep 02 '26 12:09

rom58


1 Answers

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);
like image 89
tobias_k Avatar answered Sep 05 '26 01:09

tobias_k