Use of MultiMap, Bidimap and Lazymap

Source: Internet
Author: User

First, MultiMap

In daily development work, we sometimes need to construct data structures such as map<k, list<v>> or map<k, set<v>> , which are more complex types of collections, To do the appropriate business logic processing.

But like map<string, list<studentscore>> studentscoremap = new hashmap<string, List<studentscore >> () Such a data structure that itself is too cumbersome to implement, you need to check if the key exists, does not exist when you create one, and when it is present, add a previous to the list. This process is painful, and if you want to check whether an object in the list exists, delete an object, or traverse the entire data structure, you need more code to implement it.

Guava's Multimap provides a convenient data structure that maps a key to multiple values. So that we can simply and elegantly implement the above complex data structure, let our energy and time in the implementation of business logic, rather than on the data structure, the following we specifically look at the multimap of the relevant knowledge points.

The above code and data structure are implemented with Multimap, the code structure is clear and simple, the code is as follows:

 /**** * So-called multimap, that is, a key is not a simple point to an object, but a set of objects, * Add () and remove () is the same as the normal map, just in Get () return a collection, * using Multimap,   We can easily put an indefinite number of objects on a key, and realize a pair of more. */public class Mutlimaptest {public static void main (String ... args) {multimap<string, string> Mymultimap       = Arraylistmultimap.create ();     Adding some key/value mymultimap.put ("Fruits", "Bannana");     Mymultimap.put ("Fruits", "Apple");     Mymultimap.put ("Fruits", "Pear");       Mymultimap.put ("vegetables", "carrot");     Getting the size int size = Mymultimap.size ();  SYSTEM.OUT.PRINTLN (size);    4//Getting values collection<string> fruits = mymultimap.get ("fruits"); System.out.println (fruits);    [Bannana, Apple, Pear] collection<string> vegetables = mymultimap.get ("vegetables"); SYSTEM.OUT.PRINTLN (vegetables); [Carrot]//iterating over entire mutlimap for (String value:myMultimap.values ()) {System.out.println (val    UE); }//removingA single value Mymultimap.remove ("Fruits", "Pear"); System.out.println (Mymultimap.get ("Fruits"));   [Bannana, Pear]//Remove All values for a key Mymultimap.removeall ("Fruits"); System.out.println (Mymultimap.get ("Fruits"));    [] (Empty collection!)      list<string> list = new arraylist<string> ();      list<string> valuelist = new arraylist<string> ();      List.add ("123");     List.add ("456");     List.add ("789");     MultiMap MultiMap = new Multihashmap ();     Multimap.put ("Sean", list);     Multimap.put ("Sean", "C + +");     Multimap.put ("Sean", "OO");     Multimap.put ("Sean", "Java");     Multimap.put ("Sean", ". NET");     Multimap.remove ("Sean", "C + +");    System.out.println ("Sean's skill set:" + Multimap.get ("Sean"));    Iterator Itet = ((Collection) multimap.get ("Sean")). Iterator ();      while (Itet.hasnext ()) {Object obj = Itet.next ();       if (obj instanceof List) {valuelist = (list<string>) obj; for (objecT value:valuelist) {System.out.println ("obj1:" +value);      }}else if (obj instanceof String) {System.out.println ("Value:" +obj.tostring ()); }   }      }}

Multimap also supports a range of powerful view features:

1, Asmap self multimap<k, v> map into map<k, collection<v>> view. This map view supports the Remove and modify operations, but does not support put and putall. Strictly speaking, you can call Asmap () when you want the incoming parameter to be a nonexistent key, and you want to return null instead of an empty modifiable collection. (You can force transformation Asmap (). The result type of the Get (key)-the result of the Setmultimap is turned into set, the result of the Listmultimap is converted to the list type-but the Listmultimap is converted directly to Map<k, List <V>> is not going to work. )

2, Entries view is the Multimap of all the key values in the form of Collection<map.entry<k, v>> to show.

3, keyset view is the Multimap of the key collection as a view

4. The keys view Returns a Multiset, the multiset is a view of the number of non-repeating keys. This multiset can modify multimap by supporting the removal operation instead of adding an action.

5. VALUES () view can "flatten" all the values in Multimap into a collection<v>. This operation is similar to Iterables.concat (Multimap.asmap (). values ()), except that it returns a complete collection.

Although the implementation of Multimap to map, but multimap<k, v> is not map<k, collection<v>>. Because there is a clear difference between the two: 1.multimap.get (key) must return a non-null collection.   This does not mean that Multimap uses memory to correlate these keys, instead, the returned collection is simply a view that allows elements to be added. 2. If you prefer to return NULL when a key does not exist, as in map, instead of returning an empty collection like Multimap, you can use the Asmap () returned view to get Map<k, collection<v>>.   (In this case, you have to convert the returned collection<v> to a list or set).   3.multimap.containskey (Key) returns true only if the key is present. 4.multimap.entries () returns all key-value pairs for Multimap.   But if you need key-collection key-value pairs, you have to use Asmap (). Entries (). 5.multimap.size () returns the number of entries, not the number of distinct keys. If you want to get the number of non-repeating keys, you have to use Multimap.keyset (). Size ().

Note: TheMultimap is non-thread-safe and can be referenced when converting to the full object of the thread:

Private listmultimap<long,long> map = Arraylistmultimap.create ();

Private multimap<long,long> Syncmap = Multimaps.synchronizedmultimap (map);

Second, Bidimap

/****   * So-called bidimap, literal translation is a two-way map, can be found by key value,   * can also be found by value key, which in our daily code-name matching time is very convenient:   * Because in addition to the need to find the name through the code, we often need to process the user input name, and then get its code.   * It is important to note that not only key cannot be duplicated in Bidimap, but also value.   */public      static void Demobidimap () {            System.out.println (stringutils.center ("Demobidimap", "max", "=");             Bidimap Bidimap = new Dualhashbidimap ();             Bidimap.put ("BJ", "Beijing");             Bidimap.put ("SH", "Shanghai");             Bidimap.put ("GZ", "Guangzhou");             Bidimap.put ("CD", "Chengdu");             System.out.println ("KEY-VALUE:BJ =" + Bidimap.get ("BJ"));             System.out.println ("Value-key:chengdu =" + Bidimap.getkey ("Chengdu"));             System.out.println (stringutils.repeat ("=", +));    }  

Third, Lazymap

/** the so-called lazymap, meaning that the key/value pair in this map does not exist at first and is created when called.  * We understand this: we need a map, but because the method of creating a member is very "heavy" (such as database access),  * or we only know how to create it when we call get (), or there is a lot of possibilities in the map,  * We can't get () Before adding all possible key/value pairs,  * We feel no need to initialize a map and want it to automatically process the data when necessary  * *   /@SuppressWarnings (value = {"Unchecked") }) public   static void Demolazymap ()  {         System.out.println (stringutils.center ("Demolazymap", "max", "="));         Factory Factory = new Factory () {public         Object create () {                 return new Date ();         }    };        Map lazy = lazymap.decorate (new HashMap (), factory);        SYSTEM.OUT.PRINTLN ("Map:" +lazy);//lazy is empty        System.out.println (Lazy.get ("123"));        System.out.println (Lazy.get ("345"));        System.out.println (stringutils.repeat ("=", +));    }  

Use of MultiMap, Bidimap and Lazymap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.