Skip to content
Advertisement

2 HashMaps VS HashMap contain Pair

During the development of the service, I have a problem where I need to choose one of two solutions

  • use 2 hashmaps
  • use one hash map containing a pair of values.

Currently I have an option with 2 hashmaps, however I often need to get values ​​from two hash tables using the same key.

class C {
Map<String, A> a = new HashMap<>();
Map<String, B> b = new HashMap<>();

A getA(String str){return a(str);}
B getB(String str){return b(str);}
}

I am thinking of changing the code as follows

class C {
Map<String, Pair<A, B>> a_b = new HashMap<>();
Pair<A, B> getAB(String str){return a_b.get(str);}
}

Will it be more efficient on a large hash table?

Advertisement

Answer

I think this question is not so much about efficiency or performance as it is what would make sense. And to answer what would make sense, one would have to take context into cosideration. If the values of the two hashmaps are dependant on eachother and make a logical unit which could be encapsulated into a class then use a class (or a pair if it makes more sense). If the values are not directly related and only make sense at one context as pairs but in another as separate things then consider using two maps.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement