andrewDev15 andrewDev15 - 1 year ago 128
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 Source

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

private Predicate<Item> isCorrectItem() {
    return item -> -> thing.getNumber() == item.getId());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download