137

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:

For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,..,keyN), Value) in a way that I can access the element with using get(key1,key2,...keyN).

EDIT : 3 years after posting the question, I want to add a bit more to it

I came across another way for NxN matrix.

Array indices, i and j can be represented as a single key the following way:

int key = i * N + j;
//map.put(key, a[i][j]); // queue.add(key); 

And the indices can be retrevied from the key in this way:

int i = key / N;
int j = key % N;
Crocode
  • 3,056
  • 6
  • 26
  • 31

14 Answers14

214

There are several options:

2 dimensions

Map of maps

Map<Integer, Map<Integer, V>> map = //...
//...

map.get(2).get(5);

Wrapper key object

public class Key {

    private final int x;
    private final int y;

    public Key(int x, int y) {
        this.x = x;
        this.y = y;
    }

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

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

}

Implementing equals() and hashCode() is crucial here. Then you simply use:

Map<Key, V> map = //...

and:

map.get(new Key(2, 5));

Table from Guava

Table<Integer, Integer, V> table = HashBasedTable.create();
//...

table.get(2, 5);

Table uses map of maps underneath.

N dimensions

Notice that special Key class is the only approach that scales to n-dimensions. You might also consider:

Map<List<Integer>, V> map = //...

but that's terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).

Maybe take a look at Scala where you have tuples and case classes (replacing whole Key class with one-liner).

asherbret
  • 5,439
  • 4
  • 38
  • 58
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • How to get map.get(2).get(1) and map.get(2).get(3)? – user1947415 Aug 05 '14 at 17:24
  • 3
    Hi, others have x'or the two values when doing hashCode. Why do you use 31? I thought it has something to do with 32-bit integer, but when I think about it it doesn't make sense, because x=1 and y=0 still maps to the same hashcode as x=0 and y=31 – pete Feb 13 '15 at 01:37
  • 1
    @pete Joshua Bloch, in Effective Java ch 3. s 9., recommends, "1. Store some constant nonzero value, say, 17, in an int variable called result ...", which works out better collision-wise if it's a prime. See also: http://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode – fncomp Jul 22 '15 at 20:14
  • 4
    Instead of the Wrapper key object why not use `Map.Entry` as the key? – Roland Jul 06 '17 at 13:32
  • Thanks! Would be nice to write how to `put` as well in the answer. – Atul Jul 13 '17 at 05:47
  • 2
    What about `Map, Value>` ? – Joaquin Iurchuk Feb 24 '18 at 15:48
  • 1
    note that `hashCode()` can also be implemented with a single line as `Objects.hash(x,y)` – xdavidliu Jul 19 '18 at 15:32
26

When you create your own key pair object, you should face a few thing.

First, you should be aware of implementing hashCode() and equals(). You will need to do this.

Second, when implementing hashCode(), make sure you understand how it works. The given user example

public int hashCode() {
    return this.x ^ this.y;
}

is actually one of the worst implementations you can do. The reason is simple: you have a lot of equal hashes! And the hashCode() should return int values that tend to be rare, unique at it's best. Use something like this:

public int hashCode() {
  return (X << 16) + Y;
}

This is fast and returns unique hashes for keys between -2^16 and 2^16-1 (-65536 to 65535). This fits in almost any case. Very rarely you are out of this bounds.

Third, when implementing equals() also know what it is used for and be aware of how you create your keys, since they are objects. Often you do unnecessary if statements cause you will always have the same result.

If you create keys like this: map.put(new Key(x,y),V); you will never compare the references of your keys. Cause everytime you want to acces the map, you will do something like map.get(new Key(x,y));. Therefore your equals() does not need a statement like if (this == obj). It will never occur.

Instead of if (getClass() != obj.getClass()) in your equals() better use if (!(obj instanceof this)). It will be valid even for subclasses.

So the only thing you need to compare is actually X and Y. So the best equals() implementation in this case would be:

public boolean equals (final Object O) {
  if (!(O instanceof Key)) return false;
  if (((Key) O).X != X) return false;
  if (((Key) O).Y != Y) return false;
  return true;
}

So in the end your key class is like this:

public class Key {

  public final int X;
  public final int Y;

  public Key(final int X, final int Y) {
    this.X = X;
    this.Y = Y;
  }

  public boolean equals (final Object O) {
    if (!(O instanceof Key)) return false;
    if (((Key) O).X != X) return false;
    if (((Key) O).Y != Y) return false;
    return true;
  }

  public int hashCode() {
    return (X << 16) + Y;
  }
    
}

You can give your dimension indices X and Y a public access level, due to the fact they are final and do not contain sensitive information. I'm not a 100% sure whether private access level works correctly in any case when casting the Object to a Key.

If you wonder about the finals, I declare anything as final which value is set on instancing and never changes - and therefore is an object constant.

Stephane
  • 11,836
  • 25
  • 112
  • 175
chrixle
  • 331
  • 4
  • 7
8

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Create an object called Index that takes an x and y value.

public class Index {

    private int x;
    private int y;

    public Index(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return this.x ^ this.y;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Index other = (Index) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }
}

Then have your HashMap<Index, Value> to get your result. :)

Brad
  • 9,113
  • 10
  • 44
  • 68
7

Implemented in common-collections MultiKeyMap

Mike
  • 20,010
  • 25
  • 97
  • 140
  • @Wilson I fixed the link now, waiting for peer review – computingfreak Oct 16 '18 at 01:20
  • @computingfreak seems like a favourable view came through. Hurrah! NB this is the best answer IMHO. Unless you fancy spending hours competing with the expert Apache engineers over some very useful (as ever) but ultimately mundane piece of functionality. – mike rodent Jun 04 '19 at 23:33
6

Java 7+ contains a new Map.Entry<K,V> class that you can use as key for your map (or entry for your set). Java 9+ also contains a Map.entry(K k, V v) method to easily create new Map.Entry objects.

Usage:

Map<Map.Entry<Integer,Integer>, Integer> map = new HashMap<>();
map.put(Map.entry(1, 2), 0);

There is also Pair<K, V> in javafx.util

Map<Pair<Integer,Integer>, Integer> map = new HashMap<>();
map.put(new Pair(1, 2), 0);
Rajat
  • 313
  • 1
  • 8
  • 19
4

Two possibilities. Either use a combined key:

class MyKey {
    int firstIndex;
    int secondIndex;
    // important: override hashCode() and equals()
}

Or a Map of Map:

Map<Integer, Map<Integer, Integer>> myMap;
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
  • 2
    Only use a map of maps if you don't care about performance or memory use here (i.e, the map is small), or there are many keys with the same first index - since this solution means paying the overhead of a HashMap object for every single unique first index. – BeeOnRope Feb 03 '13 at 22:29
  • 1
    To improve this answer [here](http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java) is info about overriding `hashCode` and `equals` methods. – Pshemo Feb 03 '13 at 22:31
4

Use a Pair as keys for the HashMap. JDK has no Pair, but you can either use a 3rd party libraray such as http://commons.apache.org/lang or write a Pair taype of your own.

MrSmith42
  • 9,961
  • 6
  • 38
  • 49
1

Create a value class that will represent your compound key, such as:

class Index2D {
  int first, second;

  // overrides equals and hashCode properly here
}

taking care to override equals() and hashCode() correctly. If that seems like a lot of work, you might consider some ready made generic containers, such as Pair provided by apache commons among others.

There are also many similar questions here, with other ideas, such as using Guava's Table, although allows the keys to have different types, which might be overkill (in memory use and complexity) in your case since I understand your keys are both integers.

Community
  • 1
  • 1
BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
1

If they are two integers you can try a quick and dirty trick: Map<String, ?> using the key as i+"#"+j.

If the key i+"#"+j is the same as j+"#"+i try min(i,j)+"#"+max(i,j).

Lena Bru
  • 13,521
  • 11
  • 61
  • 126
arutaku
  • 5,937
  • 1
  • 24
  • 38
  • 3
    Really bad idea. Firstly, it's just bad. Secondly, this technique will get copied for other types where different key may get mapped onto the same `String` with hilarious consequences. – Tom Hawtin - tackline Feb 03 '13 at 23:17
  • It seems to me that `i#j = j#i` when `i == j` so using the `min/max` trick won't do. – Matthieu Jun 24 '14 at 10:04
  • 1
    @Matthieu what's the difference between `5#5` and `5#5` swapped around? – enrey Apr 29 '15 at 01:56
  • @enrey None. That's what I was pointing out. It really depends on the knowledge you have on your keys. – Matthieu Apr 29 '15 at 05:13
  • @Matthieu aha I see what you mean. I think that what @arutaku meant was when you want `5#3` to have same hash like `3#5`, then you use min/max to enforce `3#5` in this order. – enrey Apr 29 '15 at 06:18
  • @enrey exactly. Unless the order is important. Again, it's all about the knowledge you have on your keys (order, duplicates, ...) – Matthieu Apr 29 '15 at 06:24
  • Another way to do it. (for NxN matrix). `int key = i * N + j;` `int i = key / N;` `int j = key % N;` – Crocode Apr 15 '16 at 03:48
  • Problem: Maps are supposed to be fast, but for every single access to a map element, the caller will have to do a slow string concatenation. Also, it will horribly fail if the keys can contain whatever separator you use, so it's of limited usefulness. – toolforger Sep 06 '22 at 10:36
1

You could create your key object something like this:

public class MapKey {

public  Object key1;
public Object key2;

public Object getKey1() {
    return key1;
}

public void setKey1(Object key1) {
    this.key1 = key1;
}

public Object getKey2() {
    return key2;
}

public void setKey2(Object key2) {
    this.key2 = key2;
}

public boolean equals(Object keyObject){

    if(keyObject==null)
        return false;

    if (keyObject.getClass()!= MapKey.class)
        return false;

    MapKey key = (MapKey)keyObject;

    if(key.key1!=null && this.key1==null)
        return false;

    if(key.key2 !=null && this.key2==null)
        return false;

    if(this.key1==null && key.key1 !=null)
        return false;

    if(this.key2==null && key.key2 !=null)
        return false;

    if(this.key1==null && key.key1==null && this.key2 !=null && key.key2 !=null)
        return this.key2.equals(key.key2);

    if(this.key2==null && key.key2==null && this.key1 !=null && key.key1 !=null)
        return this.key1.equals(key.key1);

    return (this.key1.equals(key.key1) && this.key2.equals(key2));
}

public int hashCode(){
    int key1HashCode=key1.hashCode();
    int key2HashCode=key2.hashCode();
    return key1HashCode >> 3 + key2HashCode << 5;
}

}

The advantage of this is: It will always make sure you are covering all the scenario's of Equals as well.

NOTE: Your key1 and key2 should be immutable. Only then will you be able to construct a stable key Object.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andy
  • 89
  • 6
1

You can also use guava Table implementation for this.

Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.

//create a table
  Table<String, String, String> employeeTable = HashBasedTable.create();

  //initialize the table with employee details
  employeeTable.put("IBM", "101","Mahesh");
  employeeTable.put("IBM", "102","Ramesh");
  employeeTable.put("IBM", "103","Suresh");

  employeeTable.put("Microsoft", "111","Sohan");
  employeeTable.put("Microsoft", "112","Mohan");
  employeeTable.put("Microsoft", "113","Rohan");

  employeeTable.put("TCS", "121","Ram");
  employeeTable.put("TCS", "122","Shyam");
  employeeTable.put("TCS", "123","Sunil");

  //get Map corresponding to IBM
  Map<String,String> ibmEmployees =  employeeTable.row("IBM");
slisnychyi
  • 1,832
  • 3
  • 25
  • 32
1

we can create a class to pass more than one key or value and the object of this class can be used as a parameter in map.

import java.io.BufferedReader; 
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

 public class key1 {
    String b;
    String a;
    key1(String a,String b)
    {
        this.a=a;
        this.b=b;
    }
  }

public class read2 {

private static final String FILENAME = "E:/studies/JAVA/ReadFile_Project/nn.txt";

public static void main(String[] args) {

    BufferedReader br = null;
    FileReader fr = null;
    Map<key1,String> map=new HashMap<key1,String>();
    try {

        fr = new FileReader(FILENAME);
        br = new BufferedReader(fr);

        String sCurrentLine;

        br = new BufferedReader(new FileReader(FILENAME));

        while ((sCurrentLine = br.readLine()) != null) {
            String[] s1 = sCurrentLine.split(",");
            key1 k1 = new key1(s1[0],s1[2]);
            map.put(k1,s1[2]);
        }
        for(Map.Entry<key1,String> m:map.entrySet()){  
            key1 key = m.getKey();
            String s3 = m.getValue();
               System.out.println(key.a+","+key.b+" : "+s3);  
              }  
  //            }   
        } catch (IOException e) {

        e.printStackTrace();

    } finally {

        try {

            if (br != null)
                br.close();

            if (fr != null)
                fr.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }

    }

 }
Vikas Pal
  • 11
  • 2
0

You can download it from the below link: https://github.com/VVS279/DoubleKeyHashMap/blob/master/src/com/virtualMark/doubleKeyHashMap/DoubleKeyHashMap.java

https://github.com/VVS279/DoubleKeyHashMap

You can use double key: value hashmap,

   DoubleKeyHashMap<Integer, Integer, String> doubleKeyHashMap1 = new 
   DoubleKeyHashMap<Integer, Integer, String>();

   DoubleKeyHashMap<String, String, String> doubleKeyHashMap2 = new 
   DoubleKeyHashMap<String, String, String>();
0

Using org.apache.commons.lang3.tuple.Pair is very easy;

   Map<String, Pair<String, Integer>> map= new HashMap<>(); 
   map.put("key", Pair.of("a", 1)); 
   int value = map.get("key").getRight();
   
Inanc Cakil
  • 306
  • 2
  • 9