Friday, October 3, 2025
HomeLanguagesJavabimap | Guava | Java

bimap | Guava | Java

A bimap i.e, bidirectional map is a map that preserves the uniqueness of its values as well as that of its keys. BiMaps support inverse view, which is another bimap containing the same entries as this bimap but with reversed keys and values.

Declaration : The declaration for com.google.common.collect.Bimap<K, V> interface is as :

@GwtCompatible
public interface BiMap<K, V>
extends Map<K, V>

Below given are some methods provided by Guava BiMap Interface :

Return Values & Exceptions :

  • put : Throws IllegalArgumentException if the given value is already bound to a different key in this bimap. The bimap will remain unmodified in this event.
  • forcePut : Returns the value which was previously associated with the key, which may be null, or null if there was no previous entry.
  • putAll : Throws IllegalArgumentException if an attempt to put any entry fails. Note that some map entries may have been added to the bimap before the exception was thrown.
  • values : Returns a Set, instead of the Collection specified in the Map interface, as a bimap has unique values.
  • inverse : Returns the inverse view of this bimap.

Below given is the implementation for Guava BiMap interface :




// Java code to show implementation for
// Guava BiMap interface
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
  
class GFG {
  
    // Driver method
    public static void main(String args[])
    {
  
        // Creating a BiMap with first field as
        // an Integer and second field as String
        // stuRollMap is name of BiMap
        // i.e, the first field of BiMap stores
        // the Roll no. of student and second
        // field stores the name of Student
        BiMap<Integer, String> stuRollMap = HashBiMap.create();
  
        stuRollMap.put(new Integer(2), "Sahil");
        stuRollMap.put(new Integer(6), "Dhiman");
        stuRollMap.put(new Integer(9), "Shubham");
        stuRollMap.put(new Integer(15), "Abhishek");
  
        // To display Roll no. of student "Dhiman"
        System.out.println(stuRollMap.inverse().get("Dhiman"));
  
        // To display Roll no. of student "Shubham"
        System.out.println(stuRollMap.inverse().get("Shubham"));
    }
}


Output :

6
9
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11929 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS