我们正在尝试将以下代码重构为 java 8:
List<String> list = new ArrayList<>();
Iterator<Obj> i = x.iterator();
while (i.hasNext()) {
String y = m(i.next().getKey());
if (y != null) {
list.add(y);
}
}
return list;
到目前为止,我们已经提出了:return x.stream()
.filter(s -> m(s.getKey()) != null)
.map(t -> m(t.getKey()))
.collect(Collectors.toList());
但是方法m()
在这里被调用两次。有什么办法吗?
最佳答案
那么你可以在映射步骤之后进行过滤:
x.stream()
.map(s -> m(s.getKey()))
.filter(Objects::nonNull)
.collect(Collectors.toList());
关于java-8 - Java8 : Filter and map on same method output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39122781/