javamultimap

HashMap with multiple Value


I want to implement Hash table with multiple values in java i.e

// if sample is a hashmap
sample.put(1,1);
sample.put(1,2);

and sample.get(1); will return 2 values.

How can i achieve this?


Solution

  • You can use a Multimap instead. It keeps multiple values for a key in a list. There are implementations in commons-collections and in Guava.

    Multimap<String, String> multimap = ArrayListMultimap.create();   
    multimap.put("ducks", "Huey");
    multimap.put("ducks", "Dewey");
    multimap.put("ducks", "Louie");
    Collection<String> ducks = multimap.get("ducks");
    System.out.println(ducks); // [Huey, Dewey, Louie]
    

    It is similar to using a Hashmap where the values are lists, but you don't have to explicitly create the lists.

    The same example done the do-it-yourself way looks like:

    Map<String, List<String>> map = new HashMap<>();
    map.put("ducks", new ArrayList<String>());
    map.get("ducks").add("Huey");
    map.get("ducks").add("Dewey");
    map.get("ducks").add("Louie");
    // or as an alternative to the prev 4 lines:
    // map.put("ducks", new ArrayList<String>(
    //     new String[] {"Huey", "Dewey", "Louie"}));
    Collection<String> ducks = map.get("ducks");
    System.out.println(ducks); // [Huey, Dewey, Louie]
    

    Note that you can use the Multimap as a builder and call asMap on it to return a map.