Setting a boolean flag inside Java 8 Stream

Viewed 10704

I'm wondering what the best practices are for setting a boolean flag value from a java stream. Here is an example of what I want to do:

    List<Integer> list = Arrays.asList(1,2,3,4,5);
    boolean flag = false;
    List<Integer> newList = list.stream()
                                //many other filters, flatmaps, etc...
                                .filter(i -> {
                                    if(condition(i)){
                                        flag = true;
                                    }
                                    return condition(i);
                                })
                                //many other filters, flatmaps, etc...
                                .collect(Collectors.toList());
    //do some work with the new list and the flag

However, this goes against the language restriction "Variable used in lambda expression should be final or effectively final". There are a few solutions I can think of but I'm not sure which is best. This first solution I have is adding elements that match condition to a list and checking List::isEmpty. One could also wrap flag in an AtomicReference.

Note that my question is similar to this question, but I'm trying to extract a boolean value in the end rather than setting a variable.

3 Answers
Related