I was wondering if there's an effective way to extract an array of properties from an array of custom class objects. For example if I have something like this:

public class MyClass {
    private Double p1;
    private String p2;
    private MyProperty p3;

    public MyClass() {}

and in somewhere I have an ArrayList filled with objects of this class:

ArrayList<MyClass> listOfObjects = new ArrayList<>();

and I'd like to get a list of one of the properties:

ArrayList<MyProperty> listOfP3 = new ArrayList<>();
ArrayList<Double> listOfP1 = new ArrayList<>();

All I can think of is iterating through listOfObjects and copying the desired properties one by one to a new array... Is there a better way to do this?

EDIT: If possible one that works with Java 7 also

2 Answers

Amongalen On

Probably the cleanest way to do it is to use Streams. Something like this:

List<String> listOfP2= listOfObjects.stream().map(x->x.getP2()).collect(Collectors.toList());

Of course in MyClass you need to add a getter for those fields.

deHaar On

In Java 8 and higher, you can utilize the stream API (as @Amongalen already answered). There is a different possibility of accessing methods: Instead of x -> x.getP1() you can just write MyClass::getP1:

List<Double> p1List = myObjects.stream().map(MyClass::getP1).collect(Collectors.toList());
List<String> p2List = myObjects.stream().map(MyClass::getP2).collect(Collectors.toList());
List<MyProperty> p3List = myObjects.stream().map(MyClass::getP3).collect(Collectors.toList());