Search code examples
javajava-8java-streamatomicintegeratomic-values

Java 8 variable should be final or effectively final issue


I am using Java 8 stream Iteration with a variable that should be used in other classes also. So I have used the below code.

AtomicBoolean bool = new AtomicBoolean(true);
public void testBool(){
list.stream().forEach(c->{ 
      if( c.getName() != null){
    bool.set(true);
    }
});

}

public void test(){
  if(bool.get()){
    System.out.println("value is there");
  }
}

But I heard like using the Atomic Object will be a performance hit sometimes. Is there any alternate approach to use the variables outside the forEach block with Java 8 usage? Without this am getting the error as a variable should be a final or effectively final error.

Please help me to resolve this issue.

Thanks in advance.


Solution

  • You could avoid the problem by using the lambda expression to return true or false if there are any names that are not null, and assign the result to your boolean.

    Something like this:

    boolean hasAnyWithNames = list.stream().anyMatch(c -> c.getName() != null);
    

    The choice bool is not a good one for variable name by the way.

    Edit:

    • Replaced Boolean with base type per comment.
    • Used anyMatch() instead of filter() count per comment Thanks