Joe February 2016

how to print values for multiple keys in a hashmap?

I have a hashmap that hold k,v like this:

HashMap<String, String> total=new HashMap<>();

this is how im populating the map:(in a for loop from some result of db table)

total.put(rs.getString("id"), rs.getString("name"));

Now, some keys have multiple values, I want to print for each key: key and value. so it will look something like this:

123   john

123   tom

123   jack

234   terry

234   jeniffer

345   jacob

555   sara

how can I do this please?

thanks

Answers


Andy Turner February 2016

HashMap (and, in fact, all classes implementing Map) only stores one value per key.

Quoting the Javadoc of Map:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

To store "multiple" values per key, you need a value type which is able to store multiple values, e.g. a Collection like a List or Set, so your map type might be Map<String, List<String>>.

It's a little bit clumsy to manage: you basically have to check if there is already a collection associated with a key, add an empty one if not, and then add to the collection:

// Instead of:
map.put(key, value);

// ...you'd need something like:
if (!map.containsKey(key)) {
  map.put(key, new ArrayList<String>());
}
map.get(key).add(value);

Alternatively, there are libraries like Guava which provide the Multimap, which does more like what you describe directly.

Post Status

Asked in February 2016
Viewed 3,458 times
Voted 12
Answered 1 times

Search




Leave an answer