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