Guava Study notes: multimaps

Source: Internet
Author: User

Guava Study notes: multimaps

Sometimes we need this data type Map<string,collection<string>>,guava in Multimap is to solve this kind of problem.

The realization of Multimap

Multimap provides a rich implementation, so you can use it to replace the map<k in the program, COLLECTION<V>>, the specific implementation is as follows:

Realize Key implementation Value implementation
Arraylistmultimap HashMap ArrayList
Hashmultimap HashMap HashSet
Linkedlistmultimap Linkedhashmap LinkedList
Linkedhashmultimap Linkedhashmap Linkedhashset
Treemultimap TreeMap TreeSet
Immutablelistmultimap Immutablemap Immutablelist
Immutablesetmultimap Immutablemap Immutableset

We use an example to understand how multimap is used:

Public Class Mutlimaptest {Public Static voidMain(String...Args) {Multimap<String, String>Mymultimap= Arraylistmultimap.Create();To add a key-value pairMymultimap.Put("Fruits", "Bannana");Add another element to the fruits elementMymultimap.Put("Fruits", "Apple");Mymultimap.Put("Fruits", "Pear");Mymultimap.Put("Vegetables", "Carrot");Get the size of MultimapIntSize=Mymultimap.Size();System.Out.println(Size);4Get all values corresponding to the fruitsCollection<string>Fruits=Mymultimap.Get("Fruits");System.Out.println(Fruits); [Bannana, Apple, Pear]Collection<string>Vegetables=Mymultimap.Get("Vegetables");System.Out.println(Vegetables); [Carrot]Traverse MutlimapFor(StringValue:Mymultimap.Values()) {System.Out.println(Value); }Removing a single valueMymultimap.Remove("Fruits","Pear");System.Out.println(Mymultimap.Get("Fruits")); //[Bannana, Pear]        //Remove all values for a key    mymultimap. Removeall "Fruits"     system.. Println (mymultimap. "Fruits" //[] (Empty collection!)  }  < Span class= "pun" >}             

Guava Learning Note: multimaps

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.