Java HashMap重复元素 [英] Java HashMap duplicate elements

查看:198
本文介绍了Java HashMap重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在hashmap上添加重复元素

I want to add duplicate elements on hashmap

so:

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

我该怎么做?

推荐答案

使用 Map< String,List< Integer>> 即将一个字符串映射到整数列表。

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

所以,在这种情况下, name1 将映射到[1,3,3]的列表。

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

显然,您必须编写自己的put方法,您可以在其中将int添加到列表中。示例:

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

这篇关于Java HashMap重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆