Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

map - Java HashMap duplicate elements

I want to add duplicate elements on hashmap

so:

put("name1", 1);
put("name1", 3);
put("name1", 3);
put("name2", 1);
put("name2", 3);

how i can do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a Map<String, List<Integer>> i.e. you map a string to a list of integers.

So, in this case, name1 would map to a list of [1,3,3].

Obviously you'd have to write your own put method, in which you add the int to the list. Example:

put(String s, int i){
    List<Integer> list = map.get(s);
    if(list == null){
        list = new ArrayList<Integer>();
        map.put(s, list);
    }
    list.add(i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...