0

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]

10
  • 2
    I don't think there is. You'll have to iterate over myList and extract the objects you want Commented Mar 8, 2017 at 19:42
  • 2
    Just a side note: I don't see a reason to call super() when your class doesn't actually extend any other class. Commented Mar 8, 2017 at 19:44
  • 5
    myList.stream().map(myObj::getFoo).collect(Collectors.toList()). Don't use arrays. Use lists. Commented Mar 8, 2017 at 19:45
  • Are you trying to serialize a json? There are ways to ignore attributes depending on the library that you are using. Commented Mar 8, 2017 at 19:46
  • @domdom Yes, i know, but Java's good pratice tells to do it, just for pratice btw Commented Mar 8, 2017 at 19:46

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.