KpsLok
KpsLok

Reputation: 903

How to extract an array of only one attribute from a List

I always need to extract an array of any kind of object from a list, let me explain with code:

This is my list:

List<myObj> myList = new ArrayList<myObj>();

My object has 2 objects, 'foo' and 'bar':

public class myObj{

    private Object foo;
    private Object bar;

    public myObj(Object foo, Object bar) {
        super();
        this.foo = foo;
        this.bar = bar;
    }
}   

So, i populate myList:

myList.add(new myObj(foo1, bar1));
myList.add(new myObj(foo2, bar2));
myList.add(new myObj(foo3, bar3));

Is there any way to extract into a array just the foo's Objects without programming or creating a method for that? Example:

Return: Array [foo1, foo2, foo3]

Upvotes: 0

Views: 1493

Answers (1)

KpsLok
KpsLok

Reputation: 903

As indicated by @JB Nizet in comments:

myList.stream().map(myObj::getFoo).collect(Collectors.toList‌​()). Don't use arrays. Use lists

It solved my problem! Thank you!

Upvotes: 2

Related Questions