3
\$\begingroup\$

I want to get the key from value / and value from key ,can anyone help to do in better way ? or can we implement the below code using java enum or spring or apache enumutils or java generic ?

Note : I used to get string from frond end(.jsp) and I want to store store this value into database table as integer.

Frond end  Database table
Admin   ---   1
Manager ---   2   
Employee ---  3
import java.util.HashMap;
import java.util.Map;

public class   MyRole  {

    static HashMap<Integer,String> result= new HashMap<Integer,String>();
    static{
    result.put(1,"Admin");
    result.put(2,"Manager");
    }

    public static int getId(String role){
          Integer key=-1;
          for(Map.Entry entry: result.entrySet()){
                if(role.equals(entry.getValue())){
                    key = (Integer) entry.getKey();
                    break; 
                }
            }

      return key;

    }
    public static String getRole(int id){
        return result.get(id);
    }

    public static void main(String args[]){

        String result=MyRole.getRole(1);
        System.out.println("role name"+result);
        int roleId=MyRole.getId("Admin");
        System.out.println("role id "+roleId);
    }
}

I want make sure , whether the above program is fine or can we achieve via Java enum or generic or spring api or apache enumutils api ?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Using an enum will only help if you know all the values/keys at compile time. If your data is coming from a database, then you can't know that, so you can't use an enum.

Note that your question assumes a double-key - the String value is unique, and the int value is also unique.

There are three common ways to do this problem, the easiest way is the one you have done, and then store the data in a HashMap with the most commonly used lookup as the key, and the less-common lookup as the value. This makes it quick to find the most common search on the key, and slower, but possible, to find the value.

I would improve your code by throwing an exception when the lookups fail to find a matching value. If someone asks getRole(-1) it should throw an exception... right?

The easiest solution for this type if problem is possible if you can assume that the key domain and value domain have no overlap (a value cannot also be a key). Since your keys and values are ints and Strings, it's clear there is no overlap.

To use this solution, create a "mapping" class, call it IDRole or something:

private static final class IDRole {
    private final int id;
    private final String role;
    IDRole(int id, String role) {
        this.id = id;
        this.role = role;
    }
}

Now your class can have just one HashMap<Object,IDRole> data store, and you can save each IDRole twice, once with the ID key, and once with the Role key.

private static final HashMap<Object, IDRole> mapping = new HashMap<>();

private static final addMapping(int id, String role) {
    IDRole idr = new IDRole(id, role);
    if (mapping.putIfAbsent(id, idr) != null) {
        throw new IllegalArgumentException("Cannot add duplicate mapping for " + id);
    }
    if (mapping.putIfAbsent(role, idr) != null) {
        throw new IllegalArgumentException("Cannot add duplicate mapping for " + role);
    }
}

OK, so, with the above, you can add a mapping that maps both the key, and value, in to the HashMap.

Your lookups are now easy too:

public static String getRole(int id){
    IDRole ird = mapping.get(id);
    if (idr == null) {
        throw new IllegalArgumentException("No mapping for input ID " + id);
    }
    return idr.role;
}

The getID would be similar.

\$\endgroup\$
1
  • \$\begingroup\$ I'd suggest removing the id->idr mapping if the role->idr mapping fails. \$\endgroup\$
    – cHao
    Commented Nov 15, 2015 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.