I'm trying to filter a list based on a condition. Is there an alternative to break in java 8 streams which I can use to stop filtering?
To give an example: suppose I have the following list.
List<String> list = Arrays.asList("Foo","Food" ,"Fine","Far","Bar","Ford","Flower","Fire");
list.stream()
.filter(str -> str.startsWith("F")) //break when str doesn't start with F
.collect(Collectors.toList());
I want all strings that begin with "F" from the beginning, as soon as a string is found that does not begin with "F" I want to stop the filtering. Without streams I would do the following:
List<String> result = new ArrayList<>();
for(String s : list){
if(s.startsWith("F")){
result.add(s);
}
else{
break;
}
}
How do I use "break" in streams?