Skip to main content

Simple Reverse Lookup Enum in Java



Documentation inline with the code.


import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Intesar Mohammed
 *
 *  Reverse Enum Lookup example using Map and EnumSet
 */
public enum Status {


    WAITING(0),
    READY(1),
    SKIPPED(-1),
    COMPLETED(5);
   

   /**
    *   code or your required variable can be of any type
    */ 
    private int code;

    private Status(int code) {
        this.code = code;
    }
  
    private static final Map<Integer, Status> lookup = 
                  new HashMap<Integer, Status>();
  
    /**
     * Stores all Enum's into lookup
     */
    static {
        for (Status s : EnumSet.allOf(Status.class)) {
            lookup.put(s.code, s);
        }
    }

    /**
     *
     * toString() is the only api to print Enum value
     * All Enum classes can consistently override toString() and provide a simple api
     * across different Enums
     *
     * @return
     */
    @Override
    public String toString() {
        return String.valueOf(code);
    }

    /**
     * Sample lookup code
     *
     * Status status = Status.get(0);
     * Status status = Status.get(5);
     * Status status = Status.get(10); // this will return null
     *
     * Also you can rename get() to reverseLookup() or lookup()
     * for readability convenience
     *
     * @param code
     * @return
     */
    public static Status get(int code) {
        return lookup.get(code);
    }
}



reference

Comments

Anonymous said…
What's the advantage of using EnumSet rather than values()?
Eric Jablow said…
This won't compile unless you use generics: Map<Integer, Status> and HashMap<Integer, Status>.

It seems like unnecessary overhead, but I prefer to wrap such maps with Collections.unmodifiableMap(). It makes the intent clear.
joonas said…
Even better would be to use EnumMap instead of HashMap.
tsachev said…
I usually do the static initialisation in a separate inner static class. I know it is not very pretty, but that way you should not bother about order of your declarations.
mtrovo said…
This is very useful when you need to use Enums with a database field with checked constraint.

Do you know the class EnumMap?
It's a map optimized for Enums and it's very suitable for what you're trying to do.


Regards.
Intesar said…
EnumMap is not a good choice here as its a specialized Map implementation for use with enum type keys

also checkout jdk1.6 documentation
http://download.oracle.com/javase/6/docs/api/java/util/EnumMap.html
would have better if you could explain some usecases around it anyway something new to learn.

Javin
How Garbage collection works in Java
scardis said…
I do this type "lookup by code" logic in my enum(s) quite often, but rather than use a static block outside of the constructor, I add it to the static "lookup" Map in the constructor itself.
Sandeep said…
Thanks for this great article
Extreme Java
Indeed a useful one. Enum in Java are great feature and most versatile and very useful under certain scenario. In my opinion following are some of benefits of enum in java :
Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.
By the way I have also blogged my experience as 10 examples of enum in java , let me know how do you find it.

Popular posts from this blog

JPA 2 new feature @ElementCollection explained

@ElementCollection is new annotation introduced in JPA 2.0, This will help us get rid of One-Many and Many-One shitty syntax.

Example 1: Stores list of Strings in an Entity

@Entity
public class Users implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
@ElementCollection
    private List<String> certifications = new ArrayList<String>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<String> getCertifications() {
        return certifications;
    }

    public void setCertifications(List<String> certifications) {
        this.certifications = certifications;
    }
..
}

        Users u = new Users();
        u.getCertifications().add("Sun Certified Java Programmer");
        em.persist(u);

Generated Tables

   Users
Column --> ID
    Row             1

Users_CERTIFICATIONS

Validating CSV Files

What is CsvValidator ?
  A Java framework which validates any CSV files something similar to XML validation using XSD.

Why should I use this ?
  You don't have to use this and in fact its easy to write something your own and also checkout its source code for reference.

Why did I write this ?
  Some of our projects integrate with third party application which exchanges information in CSV files so I thought of writing a generic validator which can be hooked in multiple projects or can be used by QA for integration testing.

What is the license clause ?
GNU GPL v2

Are there any JUnit test cases for me checkout ?
 Yes, source

How to integrate in my existing project ?

Just add the Jar which can be downloaded from here CsvValidator.jar and you are good.

Instantiate CsvValidator constructor which takes these 3 arguements

         // filename is the the file to be validated and here is a sample         // list - defines all the fields in the above csv file ( a field has index, type, isOptional, rege…

ArrayList vs LinkedList vs HashSet Performance Comparision

ConclusionsInserting & Reading sequentially from Collection prefer LinkedList/ArrayListInserting & Reading/Deleting by Search/equals from Collection prefer HashSetInserting, ArrayList & LinkedList performs best while HashSet takes double the timeReading, HashSet performs best while ArrayList & LinkedList are marginally lessDeleting, HashSet performs 10 times better than ArrayList & ArrayList performs 4 times better than LinkedList. LinkedList is slow because of sequencial search Bottom line : unless you are not going to iterate using for(Integer i : list ) then prefer HashSet
Inserting/Reading/Deleting integer's from zero till countJDK7Collectionactioncounttime msArrayListInsert1000/1LinkedListInsert1000/1HashSetInsert1000/1ArrayListInsert100005LinkedListInsert100004HashSetInsert100007ArrayListInsert10000011LinkedListInsert10000011HashSetInsert10000021ArrayListGet/Read1000LinkedListGet/Read1000HashSetGet/Read1000ArrayListGet/Read100004LinkedListGet/Read100003Has…