I have the following class:
public class Item {
int id;
String name;
// few other fields, contructor, getters and setters
}
I have
If you want to stick with streams and iterate backwards, you could do it this way:
IntStream.iterate(ids.size() - 1, i -> i - 1)
.limit(ids.size())
.map(ids::get) // or .map(i -> ids.get(i))
.forEach(id -> items.stream()
.filter(item -> item.getId() == id)
.findFirst().ifPresent(item -> {
// do stuff
}));
This code does the same as yours.
It iterates backwards, starting with a seed: ids.size() - 1
. The initial stream of int
s is limited in its size with limit()
, so that there are no negative int
s and the stream has the same size as the list of ids
. Then, a map()
operation converts the index to the actual id
that is at the ith position at the ids
list (this is done by means of invoking ids.get(i)
). Finally, the item is searched in the items
list the same way as in your code.