I have the following class:
public class Item {
int id;
String name;
// few other fields, constructor, getters/setters
}
I have a list of Items. I want to iterate through the list and find the instance which has a particular id. I'm trying to do it through streams.
public void foobar() {
List<Item> items = getItemList();
List<Integer> ids = getIdsToLookup();
int id, i = ids.size() - 1;
while (i >= 0) {
id = ids.get(i);
Optional<Item> item = items
.stream()
.filter(a -> a.getId() == id)
.findFirst();
// do stuff
i--;
}
}
Is this the best way to iterate over the list and get the element I need? Also, I get an error on the filter line for id which says variables used in lambda expressions must be final or effectively final. Maybe I can define id inside the while loop, that should get rid of the exception. Thanks.
idinside the loop, and it will be effectively final. By being outside, you reinitialize it at each iteration, and it's thus not final. Declaring variables in the smallest scope possible is a best practice in general.for (int i = 0; i < ids.size(); i++), or even better and simpler:for (Integer id : ids)