guava之Lists、Maps
谷歌提供了guava包里面有很多的工具类,Lists和Maps集合工具,集合操作做了些优化提升
一、概述
1、静态工厂方法
(1)Guava提供了能够推断泛型的静态工厂方法
List list = Lists.newArrayList();
Map map = Maps.newLinkedHashMap();
(2)用工厂方法模式,我们可以方便地在初始化时就指定起始元素
Set(Type) copySet = Sets.newHashSet(elements);
List theseElements = Lists.newArrayList("alpha","beta","gamma");
(3)通过为工厂方法命名,我们可以提高集合初始化大小的可读性
List exactly100=Lists.newArrayListWithCapacity(100);
List approx100=Lists.newArrayListWithExpectedSize(100);
Set approx100Set=Sets.newHashSetWithExpectedSize(100);
2、Lists案例
public classListsTest {public static voidmain(String[] args) {
List list1 =Lists.newArrayList();for (int i = 0; i < 10; i++) {
list1.add(i+"");
}
System.out.println("list1:"+list1);//传入多参数
List list2 = Lists.newArrayList("1", "2", "3");
System.out.println("list2:"+list2);//传入数组
List list3=Lists.newArrayList(new String[]{"22","33"});
System.out.println("list3:"+list3);//传入集合
List list4=Lists.newArrayList(list1);
System.out.println("list4:"+list4);//使用条件:你确定你的容器会装多少个,不确定就用一般形式的//说明:这个容器超过10个还是会自动扩容,不用担心容量不够用,默认是分配一个容量为10的数组,不够将扩容//整个来说的优点有:节约内存,节约时间,节约性能,代码质量提高
List list=Lists.newArrayListWithExpectedSize(10);//这个方法就是直接返回一个10的数组
List list5=Lists.newArrayListWithCapacity(10);
}
}
三、Maps案例
public classMapsTest {public static voidmain(String[] args) {//1 Maps.newHashMap() 获得HashMap();
Map map1=Maps.newHashMap();for (int i = 0; i < 10; i++) {
map1.put(i,i);
}
System.out.println("map1:"+map1);//输出:map1:{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}//2、传入map1参数构建map
Map map2 =Maps.newHashMap(map1);
map2.put(10,10);
System.out.println("map2:"+map2);//输出 :map2:{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10}//3、使用条件,你确定你的容器会装多少个,不确定就用一般形式的//说明:这个容器超过3个还是会自动扩容,不用担心容量不够用,默认是分配一个容量为16的数组,不够将扩容
Map map3 = Maps.newHashMapWithExpectedSize(3);
map3.put(1,1);
map3.put(2,2);
map3.put(3,3);
System.out.println(map3);//输出: {1=1, 2=2, 3=3}//4、LinkedHashMap 有序map//Map map4 = Maps.newLinkedHashMap();//Map map4 = Maps.newLinkedHashMapWithExpectedSize(11);
Map map4 =Maps.newLinkedHashMap(map1);
map4.put(11, 11);
System.out.println("map3:" +map4);//输出:map3:{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11}
outMapKeyValue(map4);
}/*** 遍历map的四种方法
*@parammap4*/
private static void outMapKeyValue(Mapmap4){//1:通过Map.entrySet遍历key和value
for (Map.EntryintegerEntry : map4.entrySet()) {
System.out.println("key:"+integerEntry.getKey()+"value:"+integerEntry.getValue());
}//2:通过Map.entrySet使用iterator遍历key和value --不推荐,直接使用上面的for each循环替代此方法
Iterator> it =map4.entrySet().iterator();while(it.hasNext()) {
Map.Entry entry =it.next();
System.out.println("key:"+entry.getKey()+"value:"+entry.getValue());
}//3,通过Map.keySet遍历key,根据key得到value
for(Integer integer : map4.keySet()) {
System.out.println("key:"+integer+"value:"+map4.get(integer));
}//4通过Map.values遍历所有的value,但不能遍历key
for(Integer integer : map4.values()) {
System.out.println("value:"+integer);
}
}
}