0

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

Helios
  • 851
  • 2
  • 7
  • 22
Joe
  • 2,543
  • 3
  • 25
  • 49

1 Answers1

1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • i added the line that show how im populating the map, could you show me what do i need to write? – Joe Feb 08 '16 at 10:22