如何获取特定属性的值列表

拉斐尔

我想在中包含对象的某些属性的值列表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而不必ArrayList使用for循环遍历我也许与Objective-c中的valueforkey类似这将能够更方便地打印使用的值TextUtils.join(),如果我有一个ArrayList<String>包含HowCanIGet,和Those

shmosel

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

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

如果您拥有番石榴,则可以像下面这样获得列表的转换视图:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章