zoukankan      html  css  js  c++  java
  • guava学习:guava集合类型-Bimap

    学习guava让我惊喜的第二个接口就是:Bimap

    BiMap是一种特殊的映射其保持映射,同时确保没有重复的值是存在于该映射和一个值可以安全地用于获取键背面的倒数映射。

    最近开发过程中,经常会有这种根据key找value或者根据value找key 的功能,之前都是将值存储到枚举或者map中,然后通过反转的写法来实现的,直到发现了Bimap,才发现原来还有这么简便的方式。

    接口申明

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

    接口方法

    S.N.方法及说明
    1 V forcePut(K key, V value)
    另一种put的形式是默默删除,在put(K, V)运行前的任何现有条目值值。
    2 BiMap<V,K> inverse()
    返回此bimap,每一个bimap的值映射到其相关联的键的逆视图。
    3 V put(K key, V value)
    关联指定值与此映射中(可选操作)指定的键。
    4 void putAll(Map<? extends K,? extends V> map)
    将所有从指定映射此映射(可选操作)的映射。
    5 Set<V> values()
    返回此映射中包含Collection的值视图。

    使用样例

    BiMap<Integer, String> empIDNameMap = HashBiMap.create();
    
            empIDNameMap.put(new Integer(101), "Mahesh");
            empIDNameMap.put(new Integer(102), "Sohan");
            empIDNameMap.put(new Integer(103), "Ramesh");
    
            //得到101对应的value
            System.out.println(empIDNameMap.get(101));
            //得到Mahesh对应key
            System.out.println(empIDNameMap.inverse().get("Mahesh"));
            //传统map的写法
            System.out.println(getInverseMap(empIDNameMap).get("Mahesh"));
    /**
         * map反转工具类
         * @param map
         * @param <S>
         * @param <T>
         * @return
         */
        private static <S,T> Map<T,S> getInverseMap(Map<S,T> map) {
            Map<T,S> inverseMap = new HashMap<T,S>();
            for(Map.Entry<S,T> entry: map.entrySet()) {
                inverseMap.put(entry.getValue(), entry.getKey());
            }
            return inverseMap;
        }

    运行结果

    Mahesh
    101
    101

    inverse方法会返回一个反转的BiMap,但是注意这个反转的map不是新的map对象,它实现了一种视图关联,这样你对于反转后的map的所有操作都会影响原先的map对象。

    让我们继续看下面的例子

    System.out.println(empIDNameMap);
    BiMap<String,Integer> inverseMap = empIDNameMap.inverse();
    System.out.println(inverseMap);
    empIDNameMap.put(new Integer(104),"Jhone");
    System.out.println(empIDNameMap);
    System.out.println(inverseMap);
    
    inverseMap.put("Mahesh1",105);
    System.out.println(empIDNameMap);
    System.out.println(inverseMap);

    运行结果

    {101=Mahesh, 102=Sohan, 103=Ramesh}
    {Mahesh=101, Sohan=102, Ramesh=103}
    {101=Mahesh, 102=Sohan, 103=Ramesh, 104=Jhone}
    {Mahesh=101, Sohan=102, Ramesh=103, Jhone=104}
    {101=Mahesh, 102=Sohan, 103=Ramesh, 104=Jhone, 105=Mahesh1}
    {Mahesh=101, Sohan=102, Ramesh=103, Jhone=104, Mahesh1=105}

    可以看到,无论是操作empIdNameMap 还是操作inverseMap,2个map的数据都是相关联的发生变化。

  • 相关阅读:
    PCL中分割_欧式分割(1)
    如何在ROS中使用PCL(2)
    PCL超体聚类
    PCL常见错误集锦
    cv_bridge中的编码模式与实现
    Centos 安装配置gerrit
    git merge git pull时候遇到冲突解决办法git stash
    Python 虚拟环境:Virtualenv
    配置gitlab gerrit jenkins
    selinux开启关闭
  • 原文地址:https://www.cnblogs.com/blueskyli/p/9816438.html
Copyright © 2011-2022 走看看