Is there an eqivalent to break in Java 8+ streams?

Trillian :

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?

Ravindra Ranwala :

You can use the takeWhile operator in Java9 which exactly does what you need. Here's how it looks.

List<String> res = list.stream()
    .takeWhile(s -> s.startsWith("F"))
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308734&siteId=1