Guava-BiMap

Guava-BiMap

1.参考

Interface BiMap

2.实现类

EnumBiMap, EnumHashBiMap, HashBiMap, ImmutableBiMap
详见Interface BiMap

3.主要方法

3-1.put

 @CanIgnoreReturnValue
 @NullableDecl
V put(@NullableDecl
       K key,
       @NullableDecl
       V value)

基本同JDK的Map::put(K,V),当value以与另外一个key有映射关系时,会抛出异常IllegalArgumentException("bidirectional map":保证key和value的双向唯一性,因此可以通过inverse,提供双侧的映射关系),如果需要参见forcePut

3-2.putforcePut

强制put,会将原来的key删除

@CanIgnoreReturnValue
 @NullableDecl
V forcePut(@NullableDecl
            K key,
           @NullableDecl
            V value)

其他方法values()inverse() 见使用示例不再详述了

4.简单样例

public class BiMapTest {
  public static void main(String[] args) {

    //value 和key相互映射,以前的方法
    //当value有重复值或者没有保持同步时会出错
    Map<String, Integer> nameToId = Maps.newHashMap();
    Map<Integer, String> idToName = Maps.newHashMap();

    nameToId.put("Bob", 42);
    idToName.put(42, "Bob");

    BiMap<String, Integer> userId = HashBiMap.create();
    userId.put("Bob", 42);
    userId.put("Tom", 13);

    //IllegalArgumentException - if the given value is already bound to a different key in this bimap.
    //The bimap will remain unmodified in this event. To avoid this exception, call forcePut(K, V) instead.
    try {
      userId.put("Jack", 42);
    } catch (IllegalArgumentException e) {
      System.out.println("错误信息: " + e.getMessage());
    }

    //会把原来的Entry删除
    userId.forcePut("Jack", 42);

    System.out.println("Values: ");
    userId.values().forEach(iter->{
      System.out.println(iter);
    });

    System.out.println("---Entry---");
    for (Map.Entry<String, Integer> entry : userId.entrySet()) {
      System.out.println(entry.getKey() + "-->" + entry.getValue());
    }

    System.out.println("---reverse---");
    BiMap<Integer, String> idUser = userId.inverse();
    for (Map.Entry<Integer, String> entry : idUser.entrySet()) {
      System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
    //错误信息: value already present: 42
    //Values:
    //13
    //42
    //  ---Entry---
    //  Tom-->13
    //Jack-->42
    //  ---reverse---
    //  13-->Tom
    //42-->Jack
    //
  }
}

猜你喜欢

转载自blog.csdn.net/hjw199089/article/details/79069876