andrewDev15 andrewDev15 - 4 months ago 22
Java Question

Iterating over an enum in a Predicate?

I'm trying to loop over an enum in a predicate to return the proper values that I need.

Here's what I would do :

private Predicate<Item> isCorrectItem() {
for (Thing thing : Thing.values()) {
return item -> item.getId() == thing.getNumber();
}
}


except java wants a return outside of the loop aswell. Returning null after the loop won't do me any good. I'm asking, what can I do to either avoid returning twice or to avoid iterating over the enum in the first place? And if not, what
should I return?

Answer

If the Item is correct when it has a matching number in the enum Thing you can use

private Predicate<Item> isCorrectItem() {
    return item -> Arrays.stream(Thing.values()).anyMatch(thing -> thing.getNumber() == item.getId());
}