java 从 ArrayList<CustomClass> 获取 ArrayList<String>(LF 方法将字符串数据作为数组而不是 foreach 返回)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15476543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:44:12  来源:igfitidea点击:

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

javaclassarraylistget

提问by T_D

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

这是我的自定义Class(为了可读性,我翻译了名称并省略了构造函数等)

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>

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 ArrayListand not the Class.

是否可以编写自定义方法,例如ArrayList<String> names = items.getAllNames();?因为我不知道在哪里放置逻辑来解决.ArrayList而不是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?

每次我需要 ArrayList 中的某些内容时都放置 foreach 行,但它看起来很混乱。有没有干净的方法来解决这个问题?

采纳答案by Shreyos Adikari

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:

您必须提供自定义类 MyClass 的 getter,我使用 List 接口作为返回类型而不是 ArrayList,因为它更灵活。
你可以试试这个,如果有任何问题,请告诉我。
请找到代码片段:

 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.

这是你的 bean 类 MyClass,我刚刚在这里添加了 getter 和 setter。

    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;
        }


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

回答by Jeroen Vannevel

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.

您必须创建一个方法来遍历 arraylist 中的所有元素,并将每个名称添加到您将返回的第二个列表中。我还没有读过 Java 的 lambda 表达式,但如果我从我的 C# 经验中回忆起任何事情,那么你也许可以用 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;
}

回答by Milan Mendpara

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;
    }

回答by WPrecht

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.

有两个明显的解决方案,一个是中间类,比如 ClassList,它包含 MyClass 的私有 ArrayList 和对其进行操作的方法。如果您需要的不仅仅是迭代器,则特别有用。另一种解决方案是将迭代器代码放在 MyClass 类本身中。这是使用中间类。

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.

看起来米兰在 MyClass 类中添加了一个这样做的例子。所以还有另一种方式。

回答by OQJF

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

如果可以导入Apache通用实用程序包,那么可以是这样的:

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