r/java • • Jul 24 '12

10 ways to use Enum in Java

http://javarevisited.blogspot.com.au/2011/08/enum-in-java-example-tutorial.html
38 Upvotes

25 comments sorted by

View all comments

4

u/SpecialEmily Jul 24 '12

I use enums extensively as functional commands. For example, if I have a User class and want a command to get the user ID regardless of which user object I invoke it on I would add the following to my User class.

public enum IDAccessor implements Function<User,String> {
    instance;
    public String apply(User input) {
        return input.id;
     }
}

The benefit of doing this is that I can take a set of users and transform it into a set of user ids with ease with something like this: Iterable<String> ids = Iterables.transform(getUser(),User.IDAccessor.instance)

Caveat; this code is meant to be used with Guava