Maps
public class MapsExampleTest
{
@Test
public void testCreate()
{
ArrayList<String> valueList = Lists.newArrayList("1", "2", "3");
ImmutableMap<String, String> map = Maps.uniqueIndex(valueList, v -> v + "_key");
System.out.println(map);
Map<String, String> map2 = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value");
System.out.println(map2);
}
@Test
public void testTransform()
{
Map<String, String> map = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value");
Map<String, String> newMap = Maps.transformValues(map, v -> v + "_transform");
System.out.println(newMap);
assertThat(newMap.containsValue("1_value_transform"), is(true));
}
@Test
public void testFilter()
{
Map<String, String> map = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value");
Map<String, String> newMap = Maps.filterKeys(map, k -> Lists.newArrayList("1", "2").contains(k));
assertThat(newMap.containsKey("3"), is(false));
}
}
Multimaps
public class MultimapsExampleTest
{
@Test
public void testBasic()
{
LinkedListMultimap<String, String> multipleMap = LinkedListMultimap.create();
HashMap<String, String> hashMap = Maps.newHashMap();
hashMap.put("1", "1");
hashMap.put("1", "2");
assertThat(hashMap.size(), equalTo(1));
multipleMap.put("1", "1");
multipleMap.put("1", "2");
assertThat(multipleMap.size(), equalTo(2));
System.out.println(multipleMap.get("1"));
}
}
BiMap
BiMap的作用很清晰:它是一个一一映射,可以通过key得到value,也可以通过value得到key
BiMap要求key和value都唯一,如果key不唯一则覆盖key,如果value不唯一则直接报错。
public class BiMapExampleTest
{
@Test
public void testCreateAndPut()
{
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
biMap.put("1", "3");
assertThat(biMap.containsKey("1"), is(true));
assertThat(biMap.size(), equalTo(1));
try
{
biMap.put("2", "3");
fail();
} catch (Exception e)
{
e.printStackTrace();
}
}
@Test
public void testBiMapInverse()
{
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
biMap.put("2", "3");
biMap.put("3", "4");
assertThat(biMap.containsKey("1"), is(true));
assertThat(biMap.containsKey("2"), is(true));
assertThat(biMap.containsKey("3"), is(true));
assertThat(biMap.size(), equalTo(3));
BiMap<String, String> inverseKey = biMap.inverse();
assertThat(inverseKey.containsKey("2"), is(true));
assertThat(inverseKey.containsKey("3"), is(true));
assertThat(inverseKey.containsKey("4"), is(true));
assertThat(inverseKey.size(), equalTo(3));
}
@Test
public void testCreateAndForcePut()
{
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
assertThat(biMap.containsKey("1"), is(true));
biMap.forcePut("2", "2");
assertThat(biMap.containsKey("1"), is(false));
assertThat(biMap.containsKey("2"), is(true));
}
}
网友评论