java地图与重复键 [英] java map with duplicate keys

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

问题描述

我正在创建一个需要存储键值对的程序。程序需要以键的形式接受请求,并返回相应的值。

I'm creating a program that needs to store key-value pairs. The program needs to accept requests in the form of keys, and return the respective values.

问题是每个键有时会有多个值,而地图类不允许重复的键。

The problem is that there are sometimes multiple values for each key, and the map class doesn't allow for duplicate keys.

这些值是数字,所以我无法有意义地连接像我这样的字符串的值。

The values are numbers, so I can't meaningfully concatenate the values like I would with strings.

有没有一种优雅的方式来计算每个键可以有多个数值的事实?我想要每个数字都被返回,而不只是一个数字。

Is there any elegant way of accounting for the fact that there can be more than one numerical value for each key? I want each number to be returned, not just one at random.

推荐答案

$ cat YourMap.java
public class YourMap extends HashMap<String, List<Integer>> {
    public void put(String key, Integer number) {
        List<Integer> current = get(key);
        if (current == null) {
            current = new ArrayList<Integer>();
            super.put(key, current);
        }
        current.add(number);
    }

    public static void main(String args[]) {
        YourMap m = new YourMap();
        m.put("a", 1);
        m.put("a", 2);
        m.put("b", 3);
        for(Map.Entry e : m.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }
    }
}

$ java map
b -> [3]
a -> [1, 2]

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

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