New Interfaces are added to supports bidirectional Map. Using bidirectional map, a key can be lookup using value and value can be lookup using key easily.

    Interface Declaration

    Following is the declaration for

    org.apache.commons.collections4.BidiMap<K,V> interface −

    1. public interface BidiMap<K,V>
    2. extends IterableMap<K,V>

    Methods

    Sr.No. Method & Description
    1

    K getKey(Object value)

    Gets the key that is currently mapped to the specified value.

    2

    BidiMap<V,K> inverseBidiMap()

    Gets a view of this map where the keys and values are reversed.

    3

    V put(K key, V value)

    Puts the key-value pair into the map, replacing any previous pair.

    4

    K removeValue(Object value)

    Removes the key-value pair that is currently mapped to the specified value (optional operation).

    5

    Set<V> values()

    Returns a Set view of the values contained in this map.

    Methods Inherited

    This interface inherits methods from the following interfaces −

    • org.apache.commons.collections4.Get
    • org.apache.commons.collections4.IterableGet
    • org.apache.commons.collections4.Put
    • java.util.Map

    Example of BidiMap Interface

    BidiMapTester.java

    1. import org.apache.commons.collections4.BidiMap;
    2. import org.apache.commons.collections4.bidimap.TreeBidiMap;
    3.  
    4. public class BidiMapTester {
    5. public static void main(String[] args) {
    6. BidiMap<String, String> bidi = new TreeBidiMap<>();
    7.  
    8. bidi.put("One", "1");
    9. bidi.put("Two", "2");
    10. bidi.put("Three", "3");
    11.  
    12. System.out.println(bidi.get("One"));
    13. System.out.println(bidi.getKey("1"));
    14. System.out.println("Original Map: " + bidi);
    15.  
    16. bidi.removeValue("1");
    17. System.out.println("Modified Map: " + bidi);
    18. BidiMap<String, String> inversedMap = bidi.inverseBidiMap();
    19. System.out.println("Inversed Map: " + inversedMap);
    20. }
    21. }

    Output

    It will print the following result.

    1. 1
    2. One
    3. Original Map: {One=1, Three=3, Two=2}
    4. Modified Map: {Three=3, Two=2}
    5. Inversed Map: {2=Two, 3=Three}