Creating a method to check if a value exists in a generic HashMap in Java?

962 views java
2

I was trying to create a generic method for checking if an item exists within a HashMap. Simple enough concept, but Java does not like what I'm trying to do. Is this even possible? This was my attempt.

private static boolean inMap(String file, HashMap<String, Object> map) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        if (entry.getKey().equals(file)) return true;
    }
    return false;
}

This is called in the following section of code:

private static Map<String, String> files = new HashMap();
private static Map<String, BufferedImage> images = new HashMap();
private static Map<String, Texture> textures = new HashMap();
private static Map<String, Model> models = new HashMap();

public static TexturedModel loadOBJModel(String file) {
    if (inMap(file, files)) ...
}

public static Texture loadTexture(String file) {
    if (inMap(file, textures)) ...
}

I wanted this method to be generic for saving code and simplicity, as i have 4 different HashMaps to check. All of them are String keys, but they are all of different Value types as shown above.

If there is any way to make this generic, any help is welcome!

answered question

Why can't you use files.containsKey('someStringKey'); and likewise for others?

2 Answers

11

Let's make use of Map.get(Object) here, and the fact that it will return null if the key doesn't exist.

public static boolean contains(Map<?, ?> inMap, Object key) {
    return inMap.get(key) == null;
}

This will also take advantage of the O(1) access time of hashmaps without relying on an O(n) loop over entries.

posted this
3

you can write generic method using T type parameter, you can use this method for all different types of HashMap

public static <T> boolean contains(String file, T a) {
    return m.keySet().contains(file);

}

posted this

Have an answer?

JD

Please login first before posting an answer.