der*_*r00 3 java for-loop if-statement java-8 java-stream
我有这个简单的代码,我在其中使用了一个流和一个 .map() 函数。我对 id 进行空检查,并在其中添加一个continue 继续给我一个错误:在循环外继续 当我删除 continue 时,我没有收到错误,但我不知道行为是否是相同?
public List<Long> getIds(final Long[][] value){
List<Long> list = Arrays.stream(value).map(result ->{
final Long id = result[1];
if(id == null){
continue; // This part doesn't work (error: Continue outside of loop)
}
return id;
}).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
关于.streams为什么会发生这种情况的任何建议?而当我不使用流时,我可以使用continue。
该问题已被标记为重复,但事实并非如此。使用return肯定适用于forEach,其中不要求返回类型,但不适用于map。
continue在 for 循环中工作。您可以将其flatMap用作解决方法:
List<Long> list = Arrays.stream(value).flatMap(result ->{
final Long id = result[1];
return Stream.ofNullable(id);
}).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
您还可以Stream.ofNullable按照@Naman 的建议直接使用,使其更加简洁:
List<Long> list = Arrays.stream(value)
.flatMap(result -> Stream.ofNullable(result[1]))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
@Holger 我首先提出的方法的另一个更优雅的版本是在 中使用谓词filter:
List<Long> list = Arrays.stream(value)
.map(result -> result[1])
.filter(Objects::nonNull)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
801 次 |
| 最近记录: |