Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream filter local variable

Obj1 x = null;
String key = null;
while(it.hasNext()){
   x = it.next();
   key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}

This is complaining with the following message: "Local variable key must be final or effective final..." I understand the the lambda context is created at runtime and it needs variables that do not change.

How can I use the functional style to find the object in the list? I want to avoid the old fashion way of iterating over the list with while.

like image 336
tt0686 Avatar asked Jan 01 '23 01:01

tt0686


2 Answers

You can simply move the variable declarations to within the loop, thus making them effectively final:

...
while(it.hasNext()){
   Obj1 x = it.next();
   String key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}

JIT/etc makes declaring variables outside of a loop a non-issue, really.

like image 194
Rogue Avatar answered Jan 02 '23 15:01

Rogue


In this case you would just need to make key final. For instance, this should work:

while(it.hasNext()){
   Obj1 x = it.next();
   listObject.stream()
   .filter(e -> e.getKey().equals(x.getKey()))
   .findFirst().get();
}
like image 23
fjsv Avatar answered Jan 02 '23 15:01

fjsv