Key to Value / Value to Key - java
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&lt;Object,IDRole&gt; data store, and you can save each IDRole twice, once with the ID key, and once with the Role key.

private static final HashMap&lt;Object, IDRole&gt; mapping = new HashMap&lt;&gt;();

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.