Guava: Multimap, Bimap

Multimap
Multimap is a collection similar to a Map, but which may associate multiple values with a single key. So if you put the two value with the same key then multimap will map both value with the same key.

Multimap has some very useful extension like ListMultimap, SetMultimap

ArrayListMultimap implements the ListMultimap interface and uses an ArrayList to store the values for a given key.

And  HashMultimap implements the SetMultimap interface and it will not store the duplicate key-value pairs, same as Set behave.

Here is the ArrayListMultimap example.

Multimap<String, String> map1 = ArrayListMultimap.create();
map1.put("A", "Test1");
map1.put("B", "Test2");
map1.put("B", "Test3");
map1.put("A", "Test4");
map1.put("C", "Test5");
map1.put("X", "Test6");
  
Multimap<String, String> map2 = ArrayListMultimap.create();
map2.put("A", "Test1");
map2.put("A", "Test2");
map2.put("B", "Test3");
map2.put("B", "Test4");
map2.put("C", "Test5");
map2.put("Y", "Test6"); 


This ArrayListMultimap will arrange the value in the map like it shown in this image
map1
map2

some useful function provided by the Multimap.
Map<K,Collection<V>> asMap()
boolean containsEntry(Object key, Object value)
boolean containsKey(Object key)  
boolean containsValue(Object value)
static <K,V> ArrayListMultimap<K,V>   create()
Set<K> keySet()
Collection<V> values()

Here are some example code.

map1.keySet();
Output:->
["A", "B", "C", "X"]

map1.values()
Output:->
["Test1", "Test4", "Test2", "Test3", "Test5", "Test4"]

map1.entries();
Output:->
["A"="Test1", "A"="Test4", "B"="Test2", "B"="Test3", "C"="Test5", "X"="Test6"]

Working with collection some time also required the comparison and for the same purpose guava as a class MapDifference and MapDifference.ValueDifference.

How to use it !!!

MapDifference<String, ?> differenceMap = Maps.difference(map1.asMap(), map2.asMap());

differenceMap.areEqual();
Output:->
false

differenceMap.entriesDiffering();
Output:->
{"A"=(["Test1", "Test4"], ["Test1", "Test2"]), "B"=(["Test2", "Test3"], ["Test3", "Test4"])}

differenceMap.entriesInCommon();
Output:->
{"C"=["Test5"]}

differenceMap.entriesOnlyOnLeft();
Output:->
{"X"=["Test6"]}

differenceMap.entriesOnlyOnRight();
Output:->
{"Y"=["Test6"]}

BiMap
BiMap (or "bidirectional map") is a map with unique keys as well as values. Because of the uniqueness of this map we can interchange the key with value.
BiMap<String, String> languageCodes = HashBiMap.create();
languageCodes.put("en", "English");
languageCodes.put("fr", "French");
languageCodes.put("zh", "Chinese");

Like a normal map we can get the value by using it’s key
languageCodes.get("en");
Output:->
"English"
And now to get the key by using it’s vlaue
languageCodes.inverse().get("English");
Output:->
"en"

Comments

Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

CSS Specificity

Application Design Notes