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.
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.
A Multimap is a new collection type that is found in Google's Guava library for Java. A Multimap can store more than one value against a key. Both the keys and the values are stored in a collection, and considered to be alternates for Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework).
Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not.
Maps don't keep the order of items. This is the contract of MultiMap s... This is the price to pay for query-in performances. One option is to use Map<String, List<String>> instead.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With