如何获取某个属性的值列表(How can I get a list of values for a certain property)

编程入门 行业动态 更新时间:2024-10-27 00:28:12
如何获取某个属性的值列表(How can I get a list of values for a certain property)

我想在ArrayList有一个对象的某个属性的值列表。 假设我有这样一个类:

public class Foo { private String b, a, r; //Constructor... //Getters... }

然后我创建一个ArrayList<Foo> :

ArrayList<Foo> fooList = new ArrayList<>(); fooList.add(new Foo("How", "Hey", "Hey")); fooList.add(new Foo("Can", "Hey", "Hey")); fooList.add(new Foo("I", "Hey", "Hey")); fooList.add(new Foo("Get", "Hey", "Hey")); fooList.add(new Foo("Those?", "Hey", "Hey"));

在ArrayList<Foo> ,是否可以获取Foo的某个属性的List而不必使用for循环迭代我的ArrayList ? 在Objective-c中,也许某些东西与valueforkey相似 。 如果我有一个包含How , Can , I , Get和Those的ArrayList<String> ,这将使用TextUtils.join()更容易打印值。

I'd like to have a list of values for a certain property of an object inside an ArrayList. Supposing I have a class like this:

public class Foo { private String b, a, r; //Constructor... //Getters... }

Then I create an ArrayList<Foo>:

ArrayList<Foo> fooList = new ArrayList<>(); fooList.add(new Foo("How", "Hey", "Hey")); fooList.add(new Foo("Can", "Hey", "Hey")); fooList.add(new Foo("I", "Hey", "Hey")); fooList.add(new Foo("Get", "Hey", "Hey")); fooList.add(new Foo("Those?", "Hey", "Hey"));

In an ArrayList<Foo>, is it possible to get a List of a certain property of Foo without having to iterate over my ArrayList using a for loop? Maybe something simillar to valueforkey in Objective-c. This would make easier to print values using TextUtils.join() if I had an ArrayList<String> containing How, Can, I, Get, and Those.

最满意答案

使用Java 8,您可以流式传输,映射和收集:

List<String> list = fooList.stream() .map(Foo::getProp) .collect(Collectors.toList());

如果您有Guava,您可以像这样获得列表的转换视图:

List<String> list = Lists.transform(fooList, Foo::getProp);

Java 7版本:

List<String> list = Lists.transform(fooList, new Function<Foo, String>() { @Override public String apply(Foo foo) { return foo.getProp(); } });

Using Java 8, you can stream, map and collect:

List<String> list = fooList.stream() .map(Foo::getProp) .collect(Collectors.toList());

If you have Guava, you can get a transformed view of your list like this:

List<String> list = Lists.transform(fooList, Foo::getProp);

The Java 7 version:

List<String> list = Lists.transform(fooList, new Function<Foo, String>() { @Override public String apply(Foo foo) { return foo.getProp(); } });

更多推荐

本文发布于:2023-07-22 02:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   列表   list   values   property

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!