Nitish Kumar
Nitish Kumar

Reputation: 65

Store all values of Duplicate Key in Map

Map<String,Integer> map=new HashMap<String,Integer>();
map.put("A",1);
map.put("A",2);
map.put("A",3);
map.put("B",4);

Here My key is A and it will override previous value of A and give value of key A is 3. But I want to store all the values of this key like i want to store 1 ,2 and 3.Then please tell me how all these value of particular key is stored in arraylist.

Upvotes: 3

Views: 289

Answers (5)

fps
fps

Reputation: 34460

As per your requirements, you don't need a Map<String, Integer>, but a Map<String, List<Integer>> instead. In other words, you're after a multimap.

One way to achieve such data structure in Java 8+, is by using the Map.computeIfAbsent and Map.computeIfPresent methods for insertions and removals, respectively:

Map<String, List<Integer>> map = new HashMap<>(); // use diamond operator

// INSERT
map.computeIfAbsent("A", k -> new ArrayList<>()).add(1);
map.computeIfAbsent("A", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("A", k -> new ArrayList<>()).add(3);
map.computeIfAbsent("B", k -> new ArrayList<>()).add(4);

// REMOVE
map.computeIfPresent("A", (k, v) -> {
    v.remove(1);
    return v.isEmpty() ? null : v;
});
map.computeIfPresent("A", (k, v) -> {
    v.remove(2);
    return v.isEmpty() ? null : v;
});
map.computeIfPresent("A", (k, v) -> {
    v.remove(3);
    return v.isEmpty() ? null : v;
});
map.computeIfPresent("B", (k, v) -> {
    v.remove(4);
    return v.isEmpty() ? null : v;
});

EDIT:

The remapping function argument for the removals could be extarcted out to the following utility method:

static <K, V> BiFunction<K, List<V>> removing(V elem) {
    return (k, v) -> { v.remove(elem); return v.isEmpty() ? null : v; };
}

Which could then be used as follows:

map.computeIfPresent("A", removing(1));
map.computeIfPresent("A", removing(2));
map.computeIfPresent("A", removing(3));
map.computeIfPresent("B", removing(4));

Upvotes: 0

nits.kk
nits.kk

Reputation: 5316

Lets analyze the requirement

  1. You have a key of type String which is needed to map with a collection(unique) of values of type Integer. (unique is my assumption). I mean ("xyz", 1) and ("xyz,1) in case of these two entries in the map it has to be seen as only one entry.
  2. From point 1 we can define a structure for an entry : [ Key- String , Value- Set ]
  3. A map is needed to hold entries of type as mentioned in point 2.

We can have a map like below.

HashMap <String, Set<Integer>> 

Lets translate it to easiest implementation, although there may be other options too.

  private Map<String, Set<Integer>> map = new HashMap<>();

  public void putPair( String key, Integer value){
          Set<Integer> values = map.get(key);
          if(values == null){
               values = new HashSet<Integer>();
                map.put(key, values);
          }
          values.add(value);
   }

In case multiple same values also you want you can use simple ArrayList instead of Set. But this case better way is to encapsulate the Integer in another wrapper class and keep a count. increment the count in case of same entry.

Upvotes: 0

javapedia.net
javapedia.net

Reputation: 2731

Try this and hope it helps.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapwithDupKeys {

    public static void main(String[] args) {

        Map<String, List<Integer>> myMultiMap = new HashMap<>();
        add(myMultiMap, "A", 1);
        add(myMultiMap, "A", 2);
        add(myMultiMap, "A", 3);
        add(myMultiMap, "B", 4);
        System.out.println(myMultiMap);
    }

    static void add(Map<String, List<Integer>> map, String key, Integer value) {
        if (map.get(key) == null) {
            List valueList = new ArrayList();
            valueList.add(value);
            map.put(key, valueList);
        } else
            ((ArrayList) map.get(key)).add(value);
    }

}

enter image description here

Upvotes: 0

Antariksh
Antariksh

Reputation: 518

Or a much mature alternative could be Guava's multiMap.

You can find the reference to it's usage here

Hope it helps!

Upvotes: 0

skipper45
skipper45

Reputation: 11

That doesn’t work in this way. Map keys are unique by definition. You will need a Map<String, List<Integer>> Of course before you add a key you need to lookup if an entry already exists. If not, add a new Arraylist using the key, and add the value to the new list.

Upvotes: 1

Related Questions