在项目里面使用guava能够是我们的代码更优雅,美观,也更有效率;
guava的扩展集合类功能很强大,日常很多JDK无法实现的,没有的集合可以使用guava集合实现;
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>19.0version>
dependency>
//创建集合
List<Object> list = Lists.newArrayList();
Set<Object> set = Sets.newHashSet();
Map<Object, Object> map = Maps.newHashMap();
//也可直接进行初始化
List<Object> list = Lists.newArrayList("a", "b", "c", "d");
@Test
public void ImmutableTest(){
//1、使用静态of方法创建
ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
//2、使用静态内部类Builder创建
ImmutableList<String> list = ImmutableList .<String>builder()
.add("a")
.add("b")
.add("c")
.build();
Map<String,Object> immutableMap = new ImmutableMap.Builder<String,Object>()
.put("k1",o1)
.put("k2",o2)
.build();
}
@Test
public void MultiMapTest(){
Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("a", 1);
multimap.put("a", 2);
multimap.put("a", 3);
multimap.put("b", 4);
multimap.put("c", 5);
System.out.println(multimap.keys());
System.out.println(multimap);
System.out.println(multimap.asMap());
}
结果:
//第一个是获取map的键
//Multimap 可以一键存多值
[a x 3, b, c]
{
a=[1, 2, 3], b=[4], c=[5]}
@Test
public void TableTest(){
Table<String, String, Integer> tables = HashBasedTable.create();
tables.put("a", "aa", 1);
tables.put("b", "bb", 2);
tables.put("c", "cc", 3);
//通过两个key获取值
Integer integer = tables.get("b", "bb");
System.out.println(tables);
System.out.println(integer);
}
结果:
{
a={
aa=1}, b={
bb=2}, c={
cc=3}}
2
@Test
public void BitMapTest(){
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("a", 1);
biMap.put("b", 2);
biMap.put("c", 3);
biMap.put("d", 1);
System.out.println(biMap);
}