从bean列表中获取属性值列表

时间:2013-10-24 10:36:59

标签: java closures javabeans

我有一个bean列表,想要获取值列表(给定一个特定的属性)。

例如,我有一个文档定义列表,我想获得一个代码列表:

List<DDocumentDef> childDefs = MDocumentDef.getChildDefinitions(document.getDocumentDef());
Collection<String> childCodes = new HashSet<String>();
for (DDocumentDef child : childDefs) {
    childCodes.add(child.getCode());
}

还有更紧凑的解决方案吗?反思,匿名内部阶级......?

提前致谢

2 个答案:

答案 0 :(得分:4)

我对你目前的做法感觉很好。

但是如果你想添加一个库(例如apache commons-collection和commons-beanutils)或者你已经添加了它,你可以这样做:

// create the transformer
BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("code" );

// transform the Collection
Collection childCodes = CollectionUtils.collect( childDefs , transformer );
来自谷歌的Guava lib提供了类似的API。

答案 1 :(得分:3)

使用标准Java API没有其他方法可以做到这一点。但是,如果您感觉舒服,可以使用Guava's Lists.transform方法:

Function<DDocumentDef, String> docToCodes = 
               new Function<DDocumentDef, String>() { 
                     public String apply(DDocumentDef docDef) { 
                         return docDef.getCode();
                     }
               };

List<String> codes = Lists.transform(childDefs, docToCodes);

或者,等到Java 8结束,然后你可以使用lambdas和stream:

List<DDocumentDef> childDefs = ...

List<String> childCodes = childDefs.stream()
                               .map(docDef -> docDef.getCode())
                               .collect(Collectors.toCollection(HashSet::new));

现在由你决定,你喜欢哪一个,你认为哪一个更短。

相关问题