A.Dev :
The Files.lines().forEach()
method doesn't allow the break
. What's the optimal way to read lines in Java 8 in chunks and break when needed?
Update 1: Example for exception.
public class Main {
public static void main(String[] args) {
try(IntStream s = IntStream.range(0, 5);){
s.forEach(i -> validate(i));
}catch(Exception ex){
System.out.println("Hello World!");
}
}
static void validate(int s){
if(s > 1){
//throw new Exception(); ?
}
System.out.println(s);
} }
Deadpool :
This is easy by using java-9 takeWhile
, So when the condition (s < 1) fails it will drop the remaining part of stream here
when an element is encountered that does not match the predicate, the rest of the stream is discarded.
s.takeWhile(s -> s < 1).forEach(System.out::println);
By using java-8 tried an example but this not every efficient as takeWhile
, by combining peek
and findFirst()
but need to have double check condition which makes no sense rather than this i will prefer standard while loop
IntStream.range(0, 5).peek(i->{
if(i<3) {
System.out.println(i);
}
}).filter(j->j>=3).findFirst();
do the action in peek and stream will break when ever predicate validated in findFirst