Java Streams -用Streams替换嵌套的for循环并返回值



我想知道如何用Java Streams代替这个老式的for循环:

public Long getStoreid(){
for (PointDto point : tw.getPath().getPoints())) {
for (PointOperationDto operation : point.getOperations()) {
if (operation.isIncluded() {
return point.getStoreId();
}
}
}
}

我需要以最好的方式得到storeId

你回答后的工作版本是:

tw.getPath().getPoints().stream()
.filter(point -> point.getOperations().stream().anyMatch(PointOperation::isIncluded))
.map(point::getStoreId)
.findFirst()
.orElse(null);

,但现在的问题是如何使用eg。Optional.ofNullable()防止NPE错误,因为tw.getPath()可以为空

我想你需要这个:

tw.getPath().getPoints().stream()
.filter(point -> point.getOperations().stream().anyMatch(Operation::isIncluded))
.map(Point::getStoreId)
.findFirst()
.orElse(0L);

mapfilterfindFirst:

public Long getStoreid() {
return tw.getPath().getPoints().stream()
.filter(Objects::isNonNull) // optional filter to prevent NPE
.map(point -> point.getOperations().stream()
.filter(Objects::isNonNull) // optional filter to prevent NPE
.filter(PointOperationDto::isIncluded)
.findFirst()
.map(op -> point.getStoreId())
)
.findFirst()
.orElse(null);
}

最新更新