Java: Composite key in hashmaps

user defined object as key in hashmap in java
java multi key map
hashmap tuple key java
java nested hashmap alternative
java map key is a pair
java map with multiple keys to one value
hashmap use pair as key
java hashmap two key

I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?

i can simply concatenate the two strings , but im sure there is a better way to do this.

You could have a custom object containing the two strings:

class StringKey {
    private String str1;
    private String str2;
}

Problem is, you need to determine the equality test and the hash code for two such objects.

Equality could be the match on both strings and the hashcode could be the hashcode of the concatenated members (this is debatable):

class StringKey {
    private String str1;
    private String str2;

    @Override
    public boolean equals(Object obj) {
        if(obj != null && obj instanceof StringKey) {
            StringKey s = (StringKey)obj;
            return str1.equals(s.str1) && str2.equals(s.str2);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return (str1 + str2).hashCode();
    }
}

Composite key in HashMaps, Composite key in HashMaps. Memory consumed by indexing a collection of objects. The time needed to randomly store that collection of objects. The time needed to recall, also randomly, all the elements of the collection. Composite key in HashMaps In my last post I talked about the problems of using an incorrect hash function when you put an object with a composite key in a Java

public int hashCode() {
    return (str1 + str2).hashCode();
}

This seems to be a terrible way to generate the hashCode: Creating a new string instance every time the hash code is computed is terrible! (Even generating the string instance once and caching the result is poor practice.)

There are a lot of suggestions here:

How do I calculate a good hash code for a list of strings?

public int hashCode() {
    final int prime = 31;
    int result = 1;
    for ( String s : strings ) {
        result = result * prime + s.hashCode();
    }
    return result;
}

For a pair of strings, that becomes:

return string1.hashCode() * 31 + string2.hashCode();

That is a very basic implementation. Lots of advice through the link to suggest better tuned strategies.

Java solution using HashMap with composite key, In this solution, I make use of a HashMap with a composite key - Tuple which encapsulates the key and the timestamp . I then iterate from the timestamp and key� You simply provide the composite keys, not a hashmap to the DBMS. My point was that databases use something similar to index their data, so it's not as if it has no useful applications for programming. But it sounds to me like a composite key hashmap is too domain specific to bother implementing something for the 'general case'.

Why not create a (say) Pair object, which contains the two strings as members, and then use this as the key ?

e.g.

public class Pair {
   private final String str1;
   private final String str2;

   // this object should be immutable to reliably perform subsequent lookups
}

Don't forget about equals() and hashCode(). See this blog entry for more on HashMaps and keys, including a background on the immutability requirements. If your key isn't immutable, then you can change its components and a subsequent lookup will fail to locate it (this is why immutable objects such as String are good candidates for a key)

You're right that concatenation isn't ideal. For some circumstances it'll work, but it's often an unreliable and fragile solution (e.g. is AB/C a different key from A/BC ?).

Composite key in HashMaps. In my last post I talked about the…, Sorry, after Hackernoon and freeCodeCamp problems with Medium I have decided to publish my content in my own site. Because Medium� Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

You don't need to reinvent the wheel. Simply use the Guava's HashBasedTable<R,C,V> implementation of Table<R,C,V> interface, for your need. Here is an example

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

table.put("key-1", "lock-1", 50);
table.put("lock-1", "key-1", 100);

System.out.println(table.get("key-1", "lock-1")); //prints 50
System.out.println(table.get("lock-1", "key-1")); //prints 100

table.put("key-1", "lock-1", 150); //replaces 50 with 150

Happy coding!

How to design good custom key object for HashMap, Lets make a reasoning around user defined object as key in hashmap in java. 1. The contract between hashCode() and equals(). The very basic� Important Note: If you are using Java version 1.4 or lower, the enhanced for each loop will not work since it was introduced in Java 1.5. Also, Generics was introduced in Java version 1.5. Use the following code to iterate through HashMap instead. Using a while loop:

I have a similar case. All I do is concatenate the two strings separated by a tilde ( ~ ).

So when the client calls the service function to get the object from the map, it looks like this:

MyObject getMyObject(String key1, String key2) {
    String cacheKey = key1 + "~" + key2;
    return map.get(cachekey);
}

It is simple, but it works.

Combines multiple values to form a single composite key. MultiKey , Combines multiple values to form a single composite key. Customized Map � Collections Data Structure � Java. A simple hashmap from keys to integers. It serves all basic needs of original java.util.HashMap with O(1) complexity in read operations. Full source code can be downloaded from here. To deep dive into the fundamentals of java.util.HashMap refer to this article. STEP1: Create a simple data structure with key, value and which can also extend as linked list. line #2,#3: references to

Nested maps vs. combined keys, More importantly, Maps in Java tend to consume a lot of memory. Populating a Map with Lastly, a Map that uses composite keys is easier to reason about. Composite key in HashMaps In my last post I talked about the problems of using an incorrect hash function when you put an object with a composite key in a Java HashMap , but I was stuck with the question: Which data structure is better to index those objects?

Java: Implement Composite Key Lookup for Map : twit88.com, Here is a simple tip to implement composite key lookup for Map, either HashMap or Hashtable, etc. Normally the key to a Map can be a String,� More importantly, Maps in Java tend to consume a lot of memory. Populating a Map with even more Maps will only aggravate the memory consumption issue. Lastly, a Map that uses composite keys is easier to reason about. Using composite keys will make your life easier in the most typical cases, yet some things will be harder.

Why You Shouldn't Use Complex Objects as HashMap Keys, TestClass.main(TestClass.java:50). So what happened? The HashMap stores its keys by using the hashcode of the key objects. If we print out� Java, Scala & Spring Tutorials. Detailed explanation of the concepts and in-dept code examples.

Comments
  • Are there any problems due to the hashcodes for ABC,D and AB,CD being the same? Or does the equals being different resolve that?
  • @smackfu: That depends. It would only be a problem if you have many such pairs of strings, because they will hash to the same slot in the table and make lookups less efficient.
  • @Tudor can you think of any advantage that this solution has over the solution presented by EdgeCase which basically just concatenates the two strings separated by a tilde character?
  • @Zak: Well the only difference is that I'm using the two strings concatenated and he's using a tilde between them. His version should do a better job at spreading around pairs of strings that would otherwise give the same result when concatenated. Anyway, I was just giving an example of how to produce the hashcode, I did not aim to make it efficient.
  • @Tudor, you don't need obj != null with instanceOf operator, Cheers!
  • "a new string instance every time the hash code is computed" - hahaha, well spotted!
  • does it make any difference if the hashcode is calculated by XOR instead of * and +, since the String hashCode uses most bits in the hashcode anyway?
  • XOR and other bitwise operators are faster than multiplication and addition. Whether the difference is significant in the example depends on the implementation of String.hashCode(). Also, one should be extra careful to make sure the new implementation has good properties as a hash function.
  • if we have to many entries (~77,500) it can we can found ourselves with hash collision?
  • Collisions will occur in proportion to the range of the hash function, the number of entries being hashed, the distribution of the values of the entries, how well behaved is the hash function, and the available space for the hash map. Without know more of these details, whether 77,500 entries will have many or few (or no) collisions can't be determined. Note that even with very good hash functions, collisions will likely occur. For a typical hash map implementation, what will matter is not whether any collisions occur, but how many in proportion to the total entries.
  • Yes. The OP stipulated "two strings" explicitly. Composite keys of another kind may require something far more sophisticated. But this is the right answer for the use case, IMHO. However, the "join" character needs more work: the OP did not say that these strings are "only alphanumeric" for example, so they could potentially contain the tilde character. Something very exotic from the wilder planes of Unicode might do the trick otherwise: 𒀛 or ♄ maybe.