Guava – bimap

来源:这里教程网 时间:2026-02-17 21:42:03 作者:

Guava – bimap

bimap即双向map,是一个既保留其值的唯一性又保留其键的唯一性的map。BiMaps支持 inverse view ,它是另一个bimap,包含与这个bimap相同的条目,但是键和值是相反的。

声明 : com.google.common.collect.Bimap < K, V > 接口的声明如下。

@GwtCompatiblepublic interface BiMap< **K, V** >extends Map< **K, V** >

以下是Guava BiMap接口提供的一些方法:

返回值和异常:

put : 如果给定的值已经被绑定到这个bimap的不同键上,则抛出IllegalArgumentException。在这个事件中,bimap将保持不被修改。forcePut : 返回先前与键相关的值,该值可能为空,如果没有先前的条目则为空。putAll : 如果试图放入任何条目失败,则抛出IllegalArgumentException。注意,在抛出异常之前,一些map条目可能已经被添加到bimap中。values : 返回一个Set,而不是Map接口中指定的Collection,因为一个bimap有唯一的值。inverse : 返回这个bimap的反向视图。

以下是Guava BiMap接口的实现:

// Java code to show implementation for// Guava BiMap interfaceimport 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"));    }}

输出:

69

相关推荐