Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to lambda expression with ForEach for a breaking for loop

Have the following codes with breaking behavior in a for loop:

package test;

import java.util.Arrays;
import java.util.List;

public class Test {

    private static List<Integer> integerList = Arrays.asList(1, 2, 3, 4);

    public static void main(String[] args) {
        countTo2(integerList);
    }

    public static void countTo2(List<Integer> integerList) {

        for (Integer integer : integerList) {
            System.out.println("counting " + integer);
            if (integer >= 2) {
                System.out.println("returning!");
                return;
            }
        }
    }
}

trying to express it with Lambda using forEach() will change the behavior as the for loop is not breaking anymore:

public static void countTo2(List<Integer> integerList) {

    integerList.forEach(integer -> {
        System.out.println("counting " + integer);
        if (integer >= 2) {
            System.out.println("returning!");
            return;
        }
    });
}

This actually makes sense as the return; statements are only enforced within the lambda expression itself (within the internal iteration) and not for the whole execution sequence, so is there a way to get the desired behavior (breaking the for loop) using the lambda expression?

like image 652
user892960 Avatar asked Dec 08 '25 18:12

user892960


1 Answers

The following code is logically equivalent to yours:

public static void countTo2(List<Integer> integerList) {
    integerList.stream()
               .peek(i -> System.out.println("counting " + i))
               .filter(i -> i >= 2)
               .findFirst()
               .ifPresent(i -> System.out.println("returning!"));
}

If you're confused about anything, please let me know!

like image 155
Jacob G. Avatar answered Dec 11 '25 12:12

Jacob G.