【发布时间】:2017-05-09 16:49:27
【问题描述】:
我有课
class ColumnTags {
String Name;
Collection<String> columnSemanticTags;
// constructor and getter and setters and other relevant attributes
}
我想从给定名称的 ColumnTag 列表中获取 columnSemanticTags。
对应的方法如下
public Collection<String> getTags(String colName, List<ColumnTags> colList)
{
Collection<String> tags = new ArrayList();
for(ColumnTag col:colList){
if(colName.equals(col.getName())){
tags = col.getColumnSemanticTags();
break;
}
}
return tags;
}
想要将 for 循环转换为 java 流。我试过了
tags = colList.stream().filter(col -> colName.equals(col.getName()))
.map(col -> col.getColumnSemanticTags())
.collect(Collectors.toCollection());
我收到编译错误。我不知道应该是什么 Supplier 。尝试过 ArrayList::new 。我也尝试将其转换为 ArrayList ,但没有成功。 有人可以告诉我我假设什么是错误的,或者处理这种情况的预期方法是什么。 通过该解决方案,有人可以解释为什么 .collect() 是解决此解决方案的错误方法。
【问题讨论】:
-
如果没有找到匹配项,是否有任何理由返回新的
ArrayList,而不是直接返回Collections.emptyList()?
标签: java java-8 java-stream