Java 8 stream filter local variable

Viewed 2166
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.

3 Answers

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();
}

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.

I want to avoid the old fashion way to iterate over the list through a while

Here is a way to iterate without explicit while loop:

StreamSupport.stream(spliteratorUnknownSize(it, Spliterator.ORDERED), false)
             .map(...)
             ...
Related