具有多个值的HashMap [英] HashMap with multiple Value

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

问题描述

我想在java中实现具有多个值的Hash表,即

I want to implement Hash table with multiple values in java i.e

// if sample is a hashmap
sample.put(1,1);
sample.put(1,2);

sample.get(1); 将返回2个值。

我如何实现这一目标?

推荐答案

您可以改用Multimap。它为列表中的键保留多个值。 commons-collections 番石榴

You can use a Multimap instead. It keeps multiple values for a key in a list. There are implementations in commons-collections and in Guava.

Multimap<String, String> multimap = ArrayListMultimap.create();   
multimap.put("ducks", "Huey");
multimap.put("ducks", "Dewey");
multimap.put("ducks", "Louie");
Collection<String> ducks = multimap.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

类似于使用值为列表的Hashmap ,但你不必明确地创建列表。

It is similar to using a Hashmap where the values are lists, but you don't have to explicitly create the lists.

同样的例子做了自己动手的方式:

The same example done the do-it-yourself way looks like:

Map<String, List<String>> map = new HashMap<>();
map.put("ducks", new ArrayList<String>());
map.get("ducks").add("Huey");
map.get("ducks").add("Dewey");
map.get("ducks").add("Louie");
// or as an alternative to the prev 4 lines:
// map.put("ducks", new ArrayList<String>(
//     new String[] {"Huey", "Dewey", "Louie"}));
Collection<String> ducks = map.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

请注意,您可以将Multimap用作构建器并调用 asMap 在它上面返回一张地图。

Note that you can use the Multimap as a builder and call asMap on it to return a map.

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

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