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.

有帮助吗?

解决方案

Use one of the SetMultimap implementations, for example 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. Try an implementation of SetMultimap such as HashMultimap or TreeMultimap.

There are many ways to do this. The simplest would be to use a 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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top