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;
    }

運行結果spa

Mahesh
101
101

 

inverse方法會返回一個反轉的BiMap,可是注意這個反轉的map不是新的map對象,它實現了一種視圖關聯,這樣你對於反轉後的map的全部操做都會影響原先的map對象。code

讓咱們繼續看下面的例子對象

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);

運行結果blog

{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的數據都是相關聯的發生變化。接口

相關文章
相關標籤/搜索