Apache Commons Collections Tutorial on Commons Collections BidiMap Interface

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 −

public interface bidimap<k,v>
   extends iterablemap<k,v>

methods

the methods for the bidimap interface are as follows −

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.ge.

  • org.apache.commons.collections4.iterablege.

  • org.apache.commons.collections4.pu.

  • java.util.ma.

example of bidimap interface

an example of bidimaptester.java is as follows −

import org.apache.commons.collections4.bidimap;
import org.apache.commons.collections4.bidimap.treebidimap;

public class bidimaptester {
   public static void main(string[] args) {
      bidimap>string, string< bidi = new treebidimap<>();
      
      bidi.put("one", "1");
      bidi.put("two", "2");
      bidi.put("three", "3");

      system.out.println(bidi.get("one"));
      system.out.println(bidi.getkey("1"));
      system.out.println("original map: " + bidi);
      
      bidi.removevalue("1");
      system.out.println("modified map: " + bidi);
      bidimap<string, string> inversedmap = bidi.inversebidimap();
      system.out.println("inversed map: " + inversedmap);
   }
}

output

when you run the code, you will see the following output −

1
one
original map: {one=1, three=3, two=2}
modified map: {three=3, two=2}
inversed map: {2=two, 3=three}