有人可以帮助我将以下代码转换为使用方法引用吗?我试图用这种新语法来解决问题,但是当它变得比映射到单个方法调用的单个变量更复杂时,我很快就会迷路:
getWorkspaces().stream().forEach((ws) -> {
DataStoreInfo defaultDataStore = getDefaultDataStore(ws);
if (defaultDataStore != null) {
other.setDefaultDataStore(ws, defaultDataStore);
}
});
我从这个开始,但是不起作用:)
getWorkspaces().stream()
.map(this::getDefaultDataStore)
.filter(Objects::nonNull)
.map(other::setDefaultDataStore);
编辑:“不起作用”是指IDE在“ setDefaultDataStore”下的最后一行抱怨它无法解析该方法。我希望我可以从一些可行的方法开始,但是我不知道如何到达那里。我对如何使用方法引用来调用带有2个参数的方法以及如何对其进行映射感到非常困惑。我已经转换了一些看起来像这样的代码:
getMaps().stream().forEach((m) -> {
other.add(m);
});
对此:
getMaps().forEach(other::add);
但是当事情变得更加复杂时,我迷路了。我希望有一个关于如何使用方法引用编写相同代码的明显解决方案。
您可以像这样将代码转换为lambda版本,但它并非如预期那样干净。
words.stream().map(ws -> new SimpleImmutableEntry<>(ws, getDefaultDataStore(ws)))
.filter(e -> e.getValue() != null)
.forEach(e -> setDefaultDataStore(e.getKey(), e.getValue()));
注意:e是输入的缩写。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句