[英]Associative array in java?
I want add duplicate keys in map,output like the one below: 我想在地图中添加重复键,输出如下所示:
google:Android,google:Maps,apple:iPod,apple:iPhone,apple:iOS
Is it possible in java or json? 在Java或JSON中可能吗? please help me. 请帮我。
I like the MultiMap answer above. 我喜欢上面的MultiMap答案。 But if you want to stick to the java.util collections, try a map of lists. 但是,如果您想坚持使用java.util集合,请尝试使用列表列表。
Even better than a map of lists is a map of sets, assuming you only want to allow duplicate keys and not duplicate associations . 假设您只想允许重复的键而不是重复的关联 ,则比列表的映射更好的是集合的映射。 It could be done like this: 可以这样完成:
import java.util.*;
Map<K, Set<V>> yourMap = new HashMap<K, Set<V>>();
public void add(K key, V value) {
if (!yourMap.containsKey(key)) {
yourMap.put(key, new HashSet<V>());
}
yourMap.get(key).add(value);
}
Replace K
and V
with the actual key and value types. 用实际的键和值类型替换K
和V
Map in java can never has duplicate key, however you can put multiple values for a particular key: Java中的Map永远不会有重复的键,但是您可以为特定的键放置多个值:
Map<String, List<String>> map = new HashMap<String, List<String>>();
You can also use MultivaluedMap
. 您也可以使用MultivaluedMap
。
Another good solution apart from Apache's library is to use Google's guava libraries. 除了Apache库之外,另一个好的解决方案是使用Google的guava库。 Guava implements a Multimap , and here's a blog post that explains how to use Guava's Multimaps Guava实现了Multimap ,这是一篇博客文章,解释了如何使用Guava的Multimaps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.