4

I am having problems mapping this data

          1           35
          1           30
          1           20
          2           10
          3           40
          3           25
          3           15

I tried using the HashMap but it would only map to the last occurrence of this data.

Steffan Harris
  • 9,106
  • 30
  • 75
  • 101

5 Answers5

8

The behavior of Map and HashMap you describe is the intended behavior, as other commenters note. What you want is a multimap. You can roll your own (don't do this-- other commenters suggest maps to lists, but that quickly becomes cumbersome. If you really want to roll your own, roll your own generic multimap with list/set values and hide the complexity.) or use Guava's multimap. Example:

import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;

  public static void main(String[] args) 
  {
    final SetMultimap<Integer, Integer> foo = HashMultimap.create();
    foo.put( 1,35);
    foo.put(   1,30);
    foo.put(  1,20);
    foo.put(  2,10);
    foo.put(  3,40);
    foo.put(  3,25);
    foo.put(  3,15);
    System.out.println(foo);
  }

Output:

{1=[35, 20, 30], 2=[10], 3=[25, 40, 15]}

If you want to access the values, there are a couple of ways depending on what you want to do. Just calling get(Integer key) will return a collection of the values.

Also, check out this answer, which cites lots of related goodness in Guava.

Community
  • 1
  • 1
andersoj
  • 22,406
  • 7
  • 62
  • 73
6

The documentation states:

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

Instead, you can associate a list of numbers with each key.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

You could use Map<Long, List<Long>> (or whatever type you have) to address this problem.

Art Licis
  • 3,619
  • 1
  • 29
  • 49
2

A Map only has single value for a key. You can use the Multimap interface from Guava / Google Collections to store multiple values for a key.

David Phillips
  • 10,723
  • 6
  • 41
  • 54
0

Or create a Pair< F, S > class and put them in a list

List< Pair< Integer, Integer > >

Diogo
  • 548
  • 2
  • 8