Data retrieval method for a small dataset with Java?

We must look for some data based on three input fields. Search should be quick. There are only about 20 possible search combinations. We implemented this using a static instance of HashMap, where we create a key by combining three data fields. Is there a better way to do this or is it the way to go? The code is below.

Refresh . I do not mean that this code is slow. Just curious if there is a better way to do this. I thought there might be a more elegant solution, but I'm happy to keep it in place if there are no attractive alternatives!


Create a static instance of HashMap at the class level:

private static HashMap map = new HashMap();

How do we load data into memory:

private void load(Iterator iterator) {        
    while (iterator.next()) {  
      Object o = it.next();
      key = o.getField1() + "-" + o.getField2() + "-" o.getField3();
      map.put(key, o.getData());
    }
}

And how do we view data based on three fields:

private Stirng getData(String f1, String f2, String f3) {
   String key = f1 + "-" + f2 + "-" f3;
   return map.get(key);
}
+3
7

, , , " ?" , , , . , , .

( ;-), HashMap, , . - -, 0 19 (, ). -, , , , .

+7

, :

class MapKey {
  public final String k1;
  public final String k2;
  public final String k3;

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

  public MapKey(Object o) {
    this.k1 = o.getField1(); this.k2 = o.getField2(); this.k3 = o.getField3();
  }

  public int hashCode() {
    return k1.hashCode();  // if k1 is likely to be the same, also add hashes from k2 and k3
  }
}
+3
+1

, . , , , .

. , toString(), :

field1="a-", field2="b-", field3="c" -> key="a--b--c"
field1="a", field2="-b", field3="-c" -> key="a--b--c"
+1

- . , . , , . , , . ( , Arrays.asList, - . API doc.)

+1

- Object , equals() ( hashCode()), , field1, field2 field3 .

EDIT ( ):

, hashCode(), , ( equals), . , HashMaps. , , equals().

, , hashCode() . , - field3. , field3 . HashMap , , equals(), .

, hashCode() . , . , , , . , HashMap .

EDIT2:

the question of a good hash code for this key was given in a separate question here

0
source

Since you have only 20 combinations, it is possible that the hand tool “give me the index 1..20 of this combination”, based on the knowledge of the characteristics of each combination.

Can you list the exact list of combinations?

0
source

Source: https://habr.com/ru/post/1719215/


All Articles