Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" ? Thanks.

like image 324
user710818 Avatar asked Sep 24 '13 13:09

user710818


People also ask

How do you remove duplicate values in a MultiMap in Java?

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.

What is guava MultiMap?

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).

Can map contains duplicate keys?

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.

Does MultiMap maintain order?

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.


2 Answers

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]} 
like image 113
gustafc Avatar answered Sep 24 '22 23:09

gustafc


A ListMultimap such as ArrayListMultimap allows duplicate key-value pairs. Try an implementation of SetMultimap such as HashMultimap or TreeMultimap.

like image 22
Paul Blessing Avatar answered Sep 25 '22 23:09

Paul Blessing