我想在中包含对象的某些属性的值列表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>
包含How
,Can
,I
,Get
,和Those
。
使用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] 删除。
我来说两句