JavaBits
JavaBits

Reputation: 2055

Can a Hash Map have a Key consisting of 2 values?

I have a table consisting 10 columns in database. One of the columns have alphaneumaric values which was set as a key for the hashmap which will have all the values as objects for each row in the hashmap. example : A10 (key) , rowobj(Class). Now in that same column another value is present as A10. So now if we are trying to load the values to hashmap from the tableas the key name is same will there be multiple values enrolled to that same key name?

Also can we combine the values of 2 columns to create a unique key for the hash map? How to do that?

Thanks

Upvotes: 0

Views: 4105

Answers (4)

Fgblanch
Fgblanch

Reputation: 5295

You could use a HashMap where the key is still A10 but now the value is a List.

So you could have multiple values for the same key. You only have to pay attention in the insertion that new List is created when the first element is inserted. May be something like (in pseudocode):

HashMap<String, List> myMap = new HashMap<String,List>;

for (elements to insert){

if (!myMap.containsKey(element.key()))
   ArrayList myList = new ArrayList();
   myList.add(element);
   myMap.put(element.key(), myList);
}else{
   ArrayList myList = myMap.get(element.key());
   myList.add(element);
   myMap.put(element.key(), myList);
}
}

Upvotes: 1

Arnab Datta
Arnab Datta

Reputation: 5246

If you mean that a Key x should map to a list vals (which are the values that x represents), then that is easily doable like this (didnt check the syntax, so dont expect it to compile):

//assuming that the keys are of type int and values are of type String
Map<int,List<String>> myMap = new HashMap()<int, new ArrayList()<String>>;

Upvotes: 0

Bozho
Bozho

Reputation: 597144

Two options:

  • create a wrapper object that contains all values as fields, set them, and then map.put(id, rowObject)
  • use Multimap (guava)

Upvotes: 3

Upul Bandara
Upul Bandara

Reputation: 5958

Can't you use primary key of the table as the key of your HashMap ?

Upvotes: 2

Related Questions