java - 在 Java 8 流的 filter() 和 map() 中使用相同的变量
问题描述
为了提高性能,我想在Java 8 流filter()
和map()
Java 8 流中使用相同的变量。例子-
list.stream()
.filter(var -> getAnotherObject(var).isPresent())
.map(var -> getAnotherObject(var).get())
.collect(Collectors.toList())
被调用的方法getAnotherObject()
看起来像 -
private Optional<String> getAnotherObject(String var)
在上述场景中,我必须调用该方法getAnotherObject()
两次。
如果我使用常规的 for 循环,那么我只需要调用getAnotherObject()
一次该方法。
List<String> resultList = new ArrayList<>();
for(String var : list) {
Optional<String> optionalAnotherObject = getAnotherObject(var);
if(optionalAnotherObject.isPresent()) {
String anotherObject = optionalAnotherObject.get();
resultList.add(anotherObject)
}
}
即使使用流,我也可以将所有代码放入map()
-
list.stream()
.map(var -> {
Optional<String> anotherObjectOptional = getAnotherObject(var);
if(anotherObjectOptional.isPresent()) {
return anotherObjectOptional.get();
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
但我相信必须有一种优雅的方式使用filter()
.
解决方案
你可以像这样创建一个流
list.stream()
.map(YourClass::getAnotherObject)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
YourClass 指的getAnotherObject
是定义方法的类的名称
推荐阅读
- reactjs - 在 React 应用程序中处理外部注销
- c++ - 这个表达式是 xvalue 吗?
- python-3.x - Tkinter 如何在窗口中间制作按钮
- ios - 如何使用 OpenCV 创建 iOS Objective-C 项目
- python-3.x - Cryptopals 挑战 4 个问题
- c++ - C++ 与 MATLAB 中的 Sin 和 cos 函数
- jenkins - 具有多个命名空间的 Kubernetes 集群上下文
- r - 从多个数据帧列表中提取特定列并将它们组合成r中的新数据帧
- c# - 如何在 3d 模型上移动轴
- python - Python 在主代码中调用本地函数会破坏测试中的导入?