Java 如何消除 Guava MultiMap 值中的重复项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18983463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to eliminate duplicates in Guava MultiMap values?
提问by user710818
Code:
代码:
Multimap<String, String> myMultimap = ArrayListMultimap.create();
myMultimap.put("12345", "qwer");
myMultimap.put("12345", "abcd");
myMultimap.put("12345", "qwer");
System.out.println(myMultimap);
Result:
结果:
{12345=[qwer, abcd, qwer]}
Is it possible to eliminate duplicate "qwer" ? Thanks.
是否可以消除重复的“qwer”?谢谢。
采纳答案by gustafc
Use one of the SetMultimap
implementations, for example HashMultimap
:
使用其中一种SetMultimap
实现,例如HashMultimap
:
SetMultimap<String, String> myMultimap = HashMultimap.create();
myMultimap.put("12345", "qwer");
myMultimap.put("12345", "abcd");
myMultimap.put("12345", "qwer");
System.out.println(myMultimap); // {12345=[abcd, qwer]}
回答by Paul Blessing
A ListMultimap
such as ArrayListMultimap
allows duplicate key-value pairs. Try an implementation of SetMultimap
such as HashMultimap
or TreeMultimap
.
甲ListMultimap
诸如ArrayListMultimap
允许重复的键-值对。尝试实现SetMultimap
诸如HashMultimap
or TreeMultimap
。
回答by StormeHawke
There are many ways to do this. The simplest would be to use a SetMultimap
.
有很多方法可以做到这一点。最简单的方法是使用SetMultimap
.
A JDK only solution with your given example however would be to simply use a Map<String, Set<String>>
, which would have one unique key to a Set
of unique values.
但是,对于给定示例的 JDK 唯一解决方案是简单地使用 a Map<String, Set<String>>
,它具有一个唯一键到 aSet
的唯一值。
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
The advantage of using that is you don't have to bring in data structures from outside libraries, you're strictly using the java core libraries.
使用它的好处是你不必从外部库中引入数据结构,你严格使用 java 核心库。