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]

KpsLok
  • 853
  • 9
  • 23
  • 2
    I don't think there is. You'll have to iterate over myList and extract the objects you want – alexgbelov Mar 08 '17 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. – domsson Mar 08 '17 at 19:44
  • 5
    `myList.stream().map(myObj::getFoo).collect(Collectors.toList())`. Don't use arrays. Use lists. – JB Nizet Mar 08 '17 at 19:45
  • Are you trying to serialize a json? There are ways to ignore attributes depending on the library that you are using. – Luis Lavieri Mar 08 '17 at 19:46
  • @domdom Yes, i know, but Java's good pratice tells to do it, just for pratice btw – KpsLok Mar 08 '17 at 19:46
  • @LuisLavieri Yes, my objective is get an array of foo's for send to my js – KpsLok Mar 08 '17 at 19:48
  • In that case, check [Gson](https://github.com/google/gson) and this [post](http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations) out. – Luis Lavieri Mar 08 '17 at 19:51
  • @LuisLavieri this isnt my objective. My objective is get an array of foo's. Thanks for docs. – KpsLok Mar 08 '17 at 19:53
  • You said that you wanted to serialize the object as a json to be able to use it in javascript. You don't need to build the string. – Luis Lavieri Mar 08 '17 at 19:55
  • @BrennoLeal for "practice" you can use JB Nizet solution, for production use Gson (or any other json serialization library) – niceman Mar 08 '17 at 20:10

1 Answers1

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!

KpsLok
  • 853
  • 9
  • 23