The Bimap of Guava
The role of Bimap is clear: it is a one by one mapping, which can be used to get the value of a key, or by value.
I. Overview1, Bimap and ordinary HashMap difference
(1) In the Java Collection Class library map, it is characterized by the stored key (key) is unique, and the value can not be unique, and
Bimap requires both key and value to be unique, and if key does not only overwrite key, if value is not unique then the error will be directly .
2. Case Show
Public classBimaptest { Public Static voidMain (String args[]) {//bidirectional MapBimap<integer,string> bimap=hashbimap.create (); Bimap.put (1, "Zhang San"); Bimap.put (2, "John Doe"); Bimap.put (3, "Harry"); Bimap.put (4, "Zhao Liu"); Bimap.put (5, "Li Seven"); Bimap.put (4, "little"); //Value is obtained by the key value (note that the type inside the key is based on the generic rowString value= Bimap.get (1); System.out.println ("Value with ID 1--" +value); //get the key value by value intKey= bimap.inverse (). Get ("Zhang San"); System.out.println ("Zhang San key value--" +key); //by repeating the key value, the Vakue value is overwritten. String valuename= Bimap.get (4); System.out.println ("Value with ID 4--" +valuename); }}/*Run Result: *id value of 1--Zhang San * Zhang San key value--1 *id to 4 value--Small*/
If the value is duplicated, the direct error to run is as follows:
Bimap.put (6, "small"); /** Background Direct Error * Exception in thread "main" Java.lang.IllegalArgumentException:value already present: small * At Com.google.common.collect.HashBiMap.put (hashbimap.java:285) * at Com.google.common.collect.HashBiMap.put (hashbimap.java:260) * at Com.jincou.stream.study.bimapTest.main (bimaptest.java:40) * /
If you want value to also overwrite the key value, then you can:
// The inverse method returns a reversed bimap, but note that this inverted map is not a new map object, it implements a view association so that all of your actions on the inverted map will affect the original map object. bimap.forceput (6, "small"); int key6= bimap.inverse (). Get ("small"); System.out.println ("Small key value-" +Key6);
/** background output (already put: Bimap.put (4, "small" overlay) * * Small key value--6 */
3. BIMAP Realization Class
Common implementations of Bimap are:
1, Hashbimap:key set and value set have HASHMAP implementation
2, Enumbimap:key and value must be enum types
3, Immutablebimap: Non-modifiable BIMAP
Think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Lieutenant Colonel "16"
"The beauty of Java code"---the Bimap of guava