简体   繁体   中英

Get the ArrayList<String> from ArrayList<CustomClass> (LF method to return string data as array instead of foreach)

Here's my custom Class (for readability I translated names and left away constructor etc)

public class MyClass {
    private long id;
    private String name, description;
    private int pictureId;
    ...
}

So I use this Class to store all data as an ArrayList<MyClass>

ArrayList<MyClass> items = getResources(); //fills the arraylist

I'd like to return all it's names.

Is it possible to write a custom method like ArrayList<String> names = items.getAllNames(); ? Because I have not idea where to put the logic to address the ArrayList and not the Class .

getAllNames()
{
    for (MyClass item : items){
        names.add(item.getName());
    }
}

Putting foreach lines everytime I need something from the ArrayList works, but it looks so messy. Is there a clean way to solve this?

You'll have to create a method which iterates over all elements in your arraylist and adds every name to a second list which you'll return. I haven't read into lambda expressions for Java yet, but if I recall anything from my C# experience then you might be able to do this with Java 8.

public List<String> getNames(){
  List<String> names = new ArrayList<>();
  List<MyClass> elements = getElements();

  for(MyClass s : elements){
     names.add(s.getName());
  }

  return names;
}

You have to provide getters of your custom class MyClass and I use List interface as a returned type instead of ArrayList as it is more flexible.
You can try this one and let me know in case of any concern.
Please find the code snippet:

 import java.util.ArrayList;
 import java.util.List;
   class Test{

        private List<MyClass> getResources() {
            // TODO Auto-generated method stub
                // Use your business logic over here
              ----------------------------------
            return new ArrayList<MyClass>();
        }
        // This is your method which will returns all the names
        public List<String> getAllNames(){
            List<String> names = new ArrayList<String>();
            List<MyClass> items = getResources();
            for (MyClass myClass : items) {
                names.add(myClass.getName());
            }
            return names;
        }
    }

Here is your bean class MyClass, I just added getters and setters over here.

    public class MyClass {
        private long id;
        private String name;
        private String description;
        private int pictureId;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }


     -------------------------------------
    }

try to follow this structure :

public class MyClass {
        private long id;
        private String name, description;
        private int pictureId;
        ...
    }

    public class Itemlist {
        public ArrayList<MyClass> items = new ArayList<MyClass>();

    public ArrayList<String> getAllNames()
    {
        ArrayList<String> names= new ArrayList<String>();
        for (MyClass item : items){
            names.add(item.getName());
        }
    return names;
    }

There are two obvious solutions, one is an intermediate class, say ClassList, that contains a private ArrayList of MyClass and methods to operate on same. Especially useful if you will need more than just an iterator. The other solution is to put the iterator code in the MyClass class itself. Here is using an intermediate class.

public ClassList {
    ArrayList<MyClass> list = null;

    public void ClassList () {
        if (list == null)
            list = new ArrayList<MyClass> ();
    }


    public ArrayList<String> getAllNames(ArrayList<MyClass> fred) {

        ArrayList<String> names = new ArrayList<String>();

        for (MyClass fred : items) {
            names.add(items.getName());
        }
        return names;
    }
}

Looks like Milan added an example of doing it inside the MyClass class. So there's another way.

If you can import Apache common utility package, then it can be this:

    List<String> fieldsValues=
(List<String>)CollectionUtils.collect(beanLs,new BeanToPropertyValueTransformer("fieldNameInBean"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM