Google Guava-Lists、Maps
Lists、Maps
位置:https://www.cnblogs.com/qdhxhz/p/9429769.html
Google Guava
位置:https://my.oschina.net/leejun2005/blog/172328
Lists案例
public class ListsTest {public static void main(String args[]){List list1 = Lists.newArrayList();for (int i = 0; i < 10; i++) {list1.add(i + "");}System.out.println("list1: " + list1);//输出:list1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]//2、传入多参数List list2 = Lists.newArrayList("1", "2", "3");System.out.println("list2: " + list2);//输出:list2: [1, 2, 3]//3、传入数组List list3 = Lists.newArrayList(new String[]{"22", "22"});System.out.println("list3: " + list3);//输出:list3: [22, 22]//4、传入集合List list4 = Lists.newArrayList(list1);System.out.println("list4: " + list4);//输出:list4: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]//5、使用条件:你确定你的容器会装多少个,不确定就用一般形式的//说明:这个容器超过10个还是会自动扩容的。不用担心容量不够用。默认是分配一个容量为10的数组,不够将扩容//整个来说的优点有:节约内存,节约时间,节约性能。代码质量提高。List list = Lists.newArrayListWithExpectedSize(10);//这个方法就是直接返回一个10的数组。List list_ = Lists.newArrayListWithCapacity(10);}
}
Maps案例
public class MapsTest {public static void main(String[] args) {//1、Maps.newHashMap()获得HashMap();Map map0 = Maps.newHashMap();for (int i = 0; i < 10; i++) {map0.put(i, i);}System.out.println("map0:" + map0);//输出:map0:{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}//2、传入map0参数构建mapMap map1 = Maps.newHashMap(map0);map1.put(10, 10);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, 10=10}//3、使用条件:你确定你的容器会装多少个,不确定就用一般形式的//说明:这个容器超过3个还是会自动扩容的。不用担心容量不够用。默认是分配一个容量为16的数组,不够将扩容Map map2 = Maps.newHashMapWithExpectedSize(3);map2.put(1, 1);map2.put(2, 2);map2.put(3, 3);System.out.println("map2:" + map2);//输出:map2:{1=1, 2=2, 3=3}//4、LinkedHashMap 有序map//Map map3 = Maps.newLinkedHashMap();//Map map3 = Maps.newLinkedHashMapWithExpectedSize(11);Map map3 = Maps.newLinkedHashMap(map1);map3.put(11, 11);System.out.println("map3:" + map3);//输出: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(map3);}/*** 遍历Map的四种方法*/private static void outMapKeyValue(Map map3) {//1.通过Map.entrySet遍历key和valuefor (Map.Entry integerEntry : map3.entrySet()) {System.out.println("key:" + integerEntry.getKey() + " value:" + integerEntry.getValue());}//2.通过Map.entrySet使用iterator遍历key和value-----不推荐,直接用上面的for each循环代替此方法Iterator> it = map3.entrySet().iterator();while (it.hasNext()) {Map.Entry entry = it.next();System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());}//3.通过Map.keySet遍历key;根据key得到valuefor (Integer integer : map3.keySet()) {System.out.println("key:" + integer + " value:" + map3.get(integer));}//4.通过Map.values()遍历所有的value,但不能遍历keyfor (Integer integer : map3.values()) {System.out.println("value:" + integer);}}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
