Iterate over all java enum values

From snippet wiki
Jump to navigation Jump to search

It is only a simple one liner to do something with all defined enum values of your local structure:

    public enum SERVICE {
        FIRST_ENTRY(0x0101),
        SECOND_ENTRY(0x0202),
        LAST_ENTRY(0x0909);

        private final int value;

        SERVICE(final int newValue) {
            value = newValue;
        }
        public int getValue() {
            return value;
        }
        public String toString() {
            return String.format("%04x", value & 0xffff);
        }
    }

    protected void enableServices()
    {
        EnumSet.allOf(SERVICE.class).forEach(service -> enableSingleService(service));
    }

    protected void enableSingleService(SERVICE s)
    {
        // ... do something
    }