Sunday, January 4, 2015

Google Gauva API in a one glance: BiMap,Multimap

@GwtCompatible
public interface BiMap<K,V>
extends Map<K,V>
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

@GwtCompatible
public interface Multimap<K,V>
A collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:
  • a → 1, 2
  • b → 3
... or as a single "flattened" collection of key-value pairs:
  • a → 1
  • a → 2
  • b → 3
Important: although the first interpretation resembles how most multimaps are implemented, the design of the Multimap API is based on the second form. So, using the multimap shown above as an example, the size() is 3, not 2, and thevalues() collection is [1, 2, 3], not [[1, 2], [3]]. For those times when the first style is more useful, use the multimap's asMap() view (or create a Map<K, Collection<V>> in the first place).



lets see sample code to understand how BiMap and MultiMap works

/**
* 
*/
package com.rajkrrsingh.test.guava;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Multimap;

/**
* @author rks
* @04-Jan-2015
*/
public class GuavaBiMapAndMultiMapDemo {

public static void main(String[] args) {
biMapDemo();
multiMapDemo();
}

// BiMap unique with both keys and value, will throw an exception if try to add a duplicate value
public static void biMapDemo(){
BiMap<String, String> map = HashBiMap.create();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

//map.put("key4", "value1");
//forceput to put forcefully
map.forcePut("key4", "value1");

// inverse a BiMap
BiMap<String, String> inverseMap = map.inverse();
System.out.println(inverseMap.get("value1"));
}

// MultiMap to substitute object similar to Map<String,List<String>>, do not enforce a list existance before adding an element to the list for given key
public static void multiMapDemo(){
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("key1","value1");
multimap.put("key1","value2");
multimap.put("key1","value3");
multimap.put("key1","value4");
multimap.put("key2","value1");
multimap.put("key2","value2");
multimap.put("key2","value3");
multimap.put("key3","value1");

System.out.println(multimap.get("key1").size());
}

}

No comments: