3
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.

3
  • did you look at Tries? Commented Apr 4, 2019 at 7:22
  • How about HashMap<String, Set<Integer>> Commented Apr 4, 2019 at 10:31
  • @Nitish Tiwari is there still something with which you need help. You have answers to your question, (including mine answer). Please refer them and in case of some thing still unclear please update the same for the corresponding answers in comment. You can update your question as well. If you find solution then you can accept the answer which resolves your problem the best possible way Commented Apr 8, 2019 at 18:28

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

You can find the reference to it's usage here

Hope it helps!

Comments

0

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

1 Comment

try add(myMultiMap, "A", 3); followed by add(myMultiMap, "A", 3); , you would be adding duplicate entries. The OP question is for allowing multiple values for same key which ends up making key as duplicate but if an entry is seen it is always unique. add(myMultiMap, "A", 3); followed by add(myMultiMap, "A", 4); are valid 2 entries but if both times same number is being added it should be seen as single entry
0

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.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.