if (response.getSubscriber().getGroups() != null) {
List<SPMGetGroupResponse> groupResponses = response.getSubscriber().getGroups()
.stream()
.map(groupId -> callGetGroupAPI(groupId))
.filter(r -> r.getResultCode() == CommonResult.SUCCESS.getResultCode())
.collect(toList());
在流中是否有一种方法可以使上述停止r.getResultCode不是SUCCESSFUL?
相当于
的流List<SPMGetGroupResponse> groupResponses = new ArrayList<>();
for (String groupId : groupIds) {
SPMGetGroupResponse grpResponse = callGetGroupAPI(groupId);
if (grpResponse.getResultCode() == CommonResult.SUCCESS.getResultCode()) {
groupResponses.add(grpResponse);
} else {
break;
}
}
答案 0 :(得分:1)
Java-8中没有标准方法可以做到这一点。在Java-9中,为此目的添加了名为takeWhile()
的新操作:
List<SPMGetGroupResponse> groupResponses = response.getSubscriber().getGroups()
.stream()
.map(groupId -> callGetGroupAPI(groupId))
.takeWhile(r -> r.getResultCode() == CommonResult.SUCCESS.getResultCode())
.collect(toList());
某些第三方库,包括我的库StreamEx向后移植takeWhile()
:
List<SPMGetGroupResponse> groupResponses = StreamEx.of(response.getSubscriber().getGroups())
.map(groupId -> callGetGroupAPI(groupId))
.takeWhile(r -> r.getResultCode() == CommonResult.SUCCESS.getResultCode())
.toList();