简体   繁体   English

如何消除Guava MultiMap值中的重复?

[英]How to eliminate duplicates in Guava MultiMap values?

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" ? 是否有可能消除重复的“qwer”? Thanks. 谢谢。

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]}

A ListMultimap such as ArrayListMultimap allows duplicate key-value pairs. ListMultimapArrayListMultimap允许重复的键-值对。 Try an implementation of SetMultimap such as HashMultimap or TreeMultimap . 尝试使用SetMultimap的实现,例如HashMultimapTreeMultimap

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解决方案只是使用Map<String, Set<String>> ,它将具有一Set唯一值的唯一键。

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核心库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM