Move to next item using Java 8 foreach loop in stream

后端 未结 4 567
醉话见心
醉话见心 2020-12-04 17:17

I have a problem with the stream of Java 8 foreach attempting to move on next item in loop. I cannot set the command like continue;, only return; w

4条回答
  •  独厮守ぢ
    2020-12-04 17:42

    You can use a simple if statement instead of continue. So instead of the way you have your code, you can try:

    try(Stream lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
                filteredLines = lines.filter(...).foreach(line -> {
               ...
               if(!...) {
                  // Code you want to run
               }
               // Once the code runs, it will continue anyway
        });
    }
    

    The predicate in the if statement will just be the opposite of the predicate in your if(pred) continue; statement, so just use ! (logical not).

提交回复
热议问题