java 如何从对象的 ArrayList 中获取属性列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4807490/
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-30 08:07:02  来源:igfitidea点击:

How to Get attributes list from ArrayList of objects

javaarraylist

提问by ninjasense

Suppose I have an object that looks like:

假设我有一个看起来像的对象:

public class Obj {
String foo;
String bar;
}

If I create an arraylist of type Obj and populate it, is there a way I can return a list of all the objects in the array's foo attribute from the ArrayList?

如果我创建一个 Obj 类型的数组列表并填充它,有没有办法可以从 ArrayList 返回数组的 foo 属性中所有对象的列表?

EDIT: I should have been more clear, I did not want to do this via iteration

编辑:我应该更清楚,我不想通过迭代来做到这一点

采纳答案by Brian Agnew

You'll have to iterate through your List<Obj>and collate the foo entries into a new List

您必须遍历您List<Obj>的 foo 条目并将其整理成一个新的List

e.g.

例如

List<String> foos = new ArrayList<String>();
for (Obj obj : objs) {
  foos.add(obj.foo)
}

or for Java 8 and beyond, use streams thus:

或者对于 Java 8 及更高版本,请使用流:

objs.stream().map(o -> o.foo).collect(toList());

回答by Surodip

Try this:

试试这个:

Collection<String> names = CollectionUtils.collect(personList, TransformerUtils.invokerTransformer("getName"));  

Use apache commons collection api.

使用 apache 公共资源集合 api。

回答by ColinD

Using Guavayou could create a view of the fooproperty of the objects in the Listusing Lists.transformlike this:

使用Guava,您可以fooListusing Lists.transform 中创建对象属性的视图,如下所示:

public class Obj {
  String foo;
  String bar;

  public static final Function<Obj, String> FOO = new Function<Obj, String>() {
    public String apply(Obj input) {
      return input.foo;
    }
  };
}

public void someMethod(List<Obj> objs) {
  List<String> foos = Lists.transform(objs, Obj.FOO);
  ...
}

Unlike other solutions, this is purely a viewof the List<Obj>and as such it doesn't allocate a whole separate ArrayListor some such in memory and can be created in almost no time regardless of the size of your List<Obj>. Additionally, if you change the original List<Obj>, the fooslist will reflect that change.

与其他解决方案不同,这纯粹是一个视图List<Obj>因此它不会ArrayList在内存中分配一个完整的单独或一些这样的内容,并且几乎可以在任何时间创建,无论List<Obj>. 此外,如果您更改原始List<Obj>foos列表将反映该更改。

In Java 8 (due in 2012 sometime), this will become a lot easier with lambda expressions and method references. You'll be able to do something like this:

在 Java 8(将于 2012 年某个时候)中,使用 lambda 表达式和方法引用将变得更加容易。你将能够做这样的事情:

List<Obj> objs = ...
List<String> foos = objs.map(#Obj.getFoo);

回答by jbandi

The answer of @Surodip uses a compact solution based on Apache Commons Collections. But that solution is not typesafe, since the Transfomer references the property via string expression: TransformerUtils.invokerTransformer("getName")

@Surodip 的答案使用基于Apache Commons Collections的紧凑解决方案。但该解决方案不是类型安全的,因为 Transfomer 通过字符串表达式引用属性:TransformerUtils.invokerTransformer("getName")

Here is a more verbose, but typesafe solution using Apache Commons Collections:

这是一个使用 Apache Commons Collections 的更详细但类型安全的解决方案:

Collection<String> values = CollectionUtils.collect(messages, new Transformer<Obj, String>(){

            @Override
            public String transform(Obj input) {
                return input.getFoo();
            }

        });

The above solutions uses Apache Commons Collection Version >= 4, which supports generics for type safety.

上述解决方案使用 Apache Commons Collection Version >= 4,它支持泛型以实现类型安全。

Below is the less typesafe version for Apache Collections Version < 4, which does not use generics:

下面是 Apache Collections Version < 4 的类型安全较少的版本,它不使用泛型:

Collection values = CollectionUtils.collect(messages, new Transformer(){

            @Override
            public Object transform(Object input) {
                Obj obj = (Obj) input;
                return obj.getFoo();
            }

        });

回答by John Gardner

something like this?

像这样的东西?

List<String> foos = new ArrayList<String>();
for (Obj obj : objList )
{
    foos.addElement(obj.foo);
}

回答by camickr

Iterate through the list and create a Set of all foo properties.

遍历列表并创建一个所有 foo 属性的集合。