Guava collections -- BiMap

来源:互联网 发布:电脑桌面时间软件 编辑:程序博客网 时间:2024/05/22 03:48

Guava全文介绍地址:Google Guava
这次主要介绍是的是com.google.common.collect.BiMap.Guava中BiMap接口是继Map。一个bimap(或称之为bidirectional map[双向Map])是一个映射,保证Map中的key值与value值的唯一性。这种约束使bimaps支持一个“inverse view”,就是另外一个bimap包含同样的entries,但是它的keys和value值是相反的。
下面就介绍一个BiMap的主要用法:

1、保证key与value的唯一性

    @Test(expected = IllegalArgumentException.class)    public void testBiMapSameValueDifferentKey() throws Exception {        BiMap<String,String> biMap = HashBiMap.create();        biMap.put("1","Tom");        biMap.put("2","Tom");    }

2、强制添加

    @Test    public void testBiMapForcePut() throws Exception {        BiMap<String,String> biMap = HashBiMap.create();        biMap.put("1","Tom");        biMap.forcePut("2","Tom");        assertThat(biMap.containsKey("1"),is(false));        assertThat(biMap.containsKey("2"),is(true));    }

3、inverse view

    @Test    public void testBiMapInverse() throws Exception {        BiMap<String,String> biMap = HashBiMap.create();        biMap.put("1","Tom");        biMap.put("2","Harry");        assertThat(biMap.get("1"),is("Tom"));        assertThat(biMap.get("2"),is("Harry"));        BiMap<String,String> inverseMap = biMap.inverse();        assertThat(inverseMap.get("Tom"),is("1"));        assertThat(inverseMap.get("Harry"),is("2"));    }

更多功能等待你的发现。

0 0
原创粉丝点击