java - 转换为流
问题描述
我想将从外部循环中断的以下代码转换为 Java 8 Stream
s。
private CPBTuple getTuple(Collection<ConsignmentAlert> alertsOnCpdDay)
{
CPBTuple cpbTuple=null;
OUTER:
for (ConsignmentAlert consignmentAlert : alertsOnCpdDay) {
List<AlertAction> alertActions = consignmentAlert.getAlertActions();
for (AlertAction alertAction : alertActions) {
cpbTuple = handleAlertAction(reportDTO, consignmentId, alertAction);
if (cpbTuple.isPresent()) {
break OUTER;
}
}
}
return cpbTuple;
}
解决方案
这里的每个答案都使用flatMap
,直到 java-10都不是懒惰的。在您的情况下,这意味着alertActions
完全遍历,而在 for 循环示例中 - 不是。这是一个简化的示例:
static class User {
private final List<String> nickNames;
public User(List<String> nickNames) {
this.nickNames = nickNames;
}
public List<String> getNickNames() {
return nickNames;
}
}
还有一些用法:
public static void main(String[] args) {
Arrays.asList(new User(Arrays.asList("one", "uno")))
.stream()
.flatMap(x -> x.getNickNames().stream())
.peek(System.out::println)
.filter(x -> x.equalsIgnoreCase("one"))
.findFirst()
.get();
}
在java-8
这将打印两个 one
and uno
,因为flatMap
不是懒惰的。
另一方面,java-10
这将打印- 如果您想将示例翻译为1 对 1 one
,这就是您关心的内容。stream-based
推荐阅读
- swift - 如何指定在 Swift 中使用泛型重载函数?
- c++ - 如何避免 nullchar 转换为 0?
- r - 两年值之间的比率
- python-3.x - Pandas Dataframe 显示问题 IBM Watson Notebook
- jquery - 使用jquery在laravel中单击按钮时如何获取foreach中数组的值索引
- spring - How not expire cache if it can't retrieve data
- ruby-on-rails - 通过 imageMagic 和 Carrierwave 获得精确尺寸
- c# - 计算交换次数和比较:选择排序
- python - 使用 pywin32 打开 powerpoint 文件时窗口不活动
- angular - 当用户转到下一页时加载数据