How to use a HashMap with two Keys? [closed]

2

I need to create a HashMap whose access form is the combination of two keys.

    
asked by Manuel Arevalo 22.08.2017 в 04:17
source

2 answers

1

There are many ways to carry it out, a couple of them recommended would be:

Double Map

Map<String, Map<String, Object>> doubleKeyMap = new HashMap<String, Map<String,Object>>();

// Agregar valores

doubleKeyMap.put("key1A", new HashMap<String, Object>(){{put("key2A", "Test");}});
doubleKeyMap.put("key1B", new HashMap<String, Object>(){{put("key2B", 123);}});
doubleKeyMap.put("key1C", new HashMap<String, Object>(){{put("key2C", false);}});

// Leer valores

doubleKeyMap.get("key1A").get("key2A"); // Test (String)
doubleKeyMap.get("key1B").get("key2B"); // 123 (int)
doubleKeyMap.get("key1C").get("key1C"); // false (boolean)
doubleKeyMap.get("key1A").get("key2B"); // null (No existe la combinación de keys)

Key Wrapper

public class Key {

    private final String k1;
    private final String k2;

    public Key(String k1, String k2) {
        this.k1 = k1;
        this.k2 = k2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Key)) return false;
        Key key = (Key) o;
        return k1.equals(key.k1) && k2.equals(key.k2);
    }

    @Override
    public int hashCode() {
        return k1.hashCode()+k2.hashCode();
    }

}

Map<Key, Object> keyWrapperMap = new HashMap<Key, Object>();

// Agregar valores

keyWrapperMap.put(new Key("key1A", "key2A"), "Test");
keyWrapperMap.put(new Key("key1B", "key2B"), 123);
keyWrapperMap.put(new Key("key1C", "key2C"), false);

// Leer valores

keyWrapperMap.get(new Key("key1A","key2A")); // Test (String)
keyWrapperMap.get(new Key("key1B","key2B")); // 123 (int)
keyWrapperMap.get(new Key("key1C","key2C")); // false (boolean)
keyWrapperMap.get(new Key("key1A","key2B")); // null (No existe la combinación de keys)
    
answered by 22.08.2017 в 11:22
-2

You can make a concatenation of your 2 values

Map<String, Object> mapa = new HashMap<>();
mapa.put("llave1" + "_" + "llave2", objeto);

Otherwise use a map where the key is an object with 2 attributes that are your keys

public class Key{
    private String key1;
    private String key2;
    public Key( String k1, String k2){
        key1 = k1;
        key2 = k2;
    }
}

And in the code, use something like this

Map<Key, Object> mapa = new HashMap<>();
mapa.put(new Key("llave1", "llave2"), objeto);
    
answered by 22.08.2017 в 05:35