@Test
public void BimapTest(){
BiMap<Integer,String> logfileMap = HashBiMap.create();
logfileMap.put(1,"a.log");
logfileMap.put(2,"b.log");
logfileMap.put(3,"c.log");
System.out.println("logfileMap:"+logfileMap);
BiMap<String,Integer> filelogMap = logfileMap.inverse();
System.out.println("filelogMap:"+filelogMap);
}
Bimap数据的强制唯一性
在使用BiMap时,会要求Value的唯一性。如果value重复了则会抛出错误:java.lang.IllegalArgumentException,例如:
@Test
public void BimapTest(){
BiMap<Integer,String> logfileMap = HashBiMap.create();
logfileMap.put(1,"a.log");
logfileMap.put(2,"b.log");
logfileMap.put(3,"c.log");
logfileMap.put(4,"d.log");
logfileMap.put(5,"d.log");
}
logfileMap.put(5,"d.log") 会抛出java.lang.IllegalArgumentException: value already present: d.log的错误。如果我们确实需要插入重复的value值,那可以选择forcePut方法。但是我们需要注意的是前面的key也会被覆盖了。
@Test
public void BimapTest(){
BiMap<Integer,String> logfileMap = HashBiMap.create();
logfileMap.put(1,"a.log");
logfileMap.put(2,"b.log");
logfileMap.put(3,"c.log");
logfileMap.put(4,"d.log");
logfileMap.forcePut(5,"d.log");
System.out.println("logfileMap:"+logfileMap);
}
输出:logfileMap:{5=d.log, 3=c.log, 2=b.log, 1=a.log}
理解inverse方法
inverse方法会返回一个反转的BiMap,但是注意这个反转的map不是新的map对象,它实现了一种视图关联,这样你对于反转后的map的所有操作都会影响原先的map对象。例如:
@Test
public void BimapTest(){
BiMap<Integer,String> logfileMap = HashBiMap.create();
logfileMap.put(1,"a.log");
logfileMap.put(2,"b.log");
logfileMap.put(3,"c.log");
System.out.println("logfileMap:"+logfileMap);
BiMap<String,Integer> filelogMap = logfileMap.inverse();
System.out.println("filelogMap:"+filelogMap);
logfileMap.put(4,"d.log");
System.out.println("logfileMap:"+logfileMap);
System.out.println("filelogMap:"+filelogMap);
}
输出:
logfileMap:{3=c.log, 2=b.log, 1=a.log}
filelogMap:{c.log=3, b.log=2, a.log=1}
logfileMap:{4=d.log, 3=c.log, 2=b.log, 1=a.log}
filelogMap:{d.log=4, c.log=3, b.log=2, a.log=1}
标签:logfileMap,log,System,笔记,BiMap,Bimap,put,Guava,filelogMap
From: https://www.cnblogs.com/junzi2099/p/17038582.html