2

I need not to remove duplicates ..

HashMap<Integer,String> hm=new HashMap();
hm.put(3,"aba");
hm.put(4,"abab");
hm.put(3,"aba");
hm.put(3,"aba");
System.out.println(hm);

Is there any way to keep duplicates in HashMap ? If not what should I do(what interface or class should i use ) if I want to do so?

10
  • 2
    You are not really removing those duplicates, you are overwriting them. If you want several different values for one key, you can create a Map<Integer, List<String>> for example... How does your desired result look? Commented Sep 4, 2020 at 11:28
  • Whole point of a Map is to keep pairs of keys and values. If you need multiple values per key, your map entry has to contain a Collection<V> as its value. Commented Sep 4, 2020 at 11:35
  • desired result: aba aba aba abab but i need to sort the key Commented Sep 4, 2020 at 11:37
  • @Shoukhin78 I updated the answer with the sort. Commented Sep 4, 2020 at 11:41
  • @Majed Badawi I want to solve a problem (with hashmap ) in codeforce . I thing If I use your approach time complexity will increase and also more memory needed. Commented Sep 4, 2020 at 11:48

1 Answer 1

1

A HashMap cannot have multiple elements with the same key. Try using an ArrayList instead:

public class Item implements Comparable<Item>{
    private int num;
    private String name;
    public Item(int num, String name) {
        this.setNum(num);
        this.setName(name);
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Item [num=" + num + ", name=" + name + "]";
    }
    @Override
    public int compareTo(Item other) {
        return this.num-other.num;
    }
}
List<Item> list=new ArrayList<>();
list.add(new Item(3,"aba"));
list.add(new Item(4,"abab"));
list.add(new Item(3,"aba"));
list.add(new Item(3,"aba"));
Collections.sort(list);
System.out.println(list.toString());

Output:

[Item [num=3, name=aba], Item [num=3, name=aba], Item [num=3, name=aba], Item [num=4, name=abab]]
Sign up to request clarification or add additional context in comments.

6 Comments

It's too early to suggest using just a list. We don't know how the map is used in general application.
@M.Prokhorov We do now: "desired result: aba aba aba abab but i need to sort the key"
Still, it generally doesn't answer the question of keeping duplicate values in Map.
@M.Prokhorov "cannot have multiple elements with the same key"
@MajedBadawi, exactly. That doesn't mean you can't store values or keep track of number of duplicates, but the value is going to be something other than String in that case.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.