Guava 之 集合工具类

Lists

public static void main(String[] args) {
     
    //指定初始大小(数据多的话会自动扩容)
    ArrayList<String> list0 = Lists.newArrayListWithCapacity(4);
    System.out.println(list0);

    ArrayList<String> list1 = Lists.newArrayList(); //能够推断泛型
    for(int i = 0;i<4;i++){
     
        list1.add(UUID.randomUUID().toString().substring(4));
    }
    list1.forEach(System.out::println);

    //传入多个参数
    ArrayList<String> list2 = Lists.newArrayList("aa", "bb", "cc");
    list2.forEach(System.out::println);

    //传入数组
    ArrayList<String> list3 = Lists.newArrayList(new String[]{
     "aa", "bb", "cc"});
    list3.forEach(System.out::println);

    //传入集合
    ArrayList<String> list4 = Lists.newArrayList(list3);
    list4.forEach(System.out::println);
}

Sets

public static void main(String[] args) {
     
    Set<Integer> set1 = Sets.newHashSet(1, 2, 3);
    Set<Integer> set2 = Sets.newHashSet(3, 4, 5);
    System.out.println("并集:" + Sets.union(set1, set2));
    System.out.println("交集:" + Sets.intersection(set1, set2));
    System.out.println("差集(set1有set2没有):" + Sets.difference(set1, set2));
    System.out.println("并集-交集:" + Sets.symmetricDifference(set1, set2));
    System.out.println("笛卡尔积:" + Sets.cartesianProduct(set1, set2));
    System.out.println("全部子集:");
    Sets.powerSet(set1).forEach(System.out::println);
}

结果:
Guava 之 集合工具类_第1张图片

Maps


```java
 public static void main(String[] args) {
     
        HashMap<String,Integer> map1 = Maps.newHashMap();// 自动推断泛型
        for (int i = 0; i < 3; i++) {
     
            map1.put(UUID.randomUUID().toString().substring(4),i+1);
        }
        map1.forEach((k,v)-> System.out.println(k+" "+v));

        //传入Map构建Map
        HashMap<String, Integer> map2 = Maps.newHashMap(map1);
        map2.forEach((k,v)-> System.out.println(k+" "+v));

        //直接指定大小
        HashMap<String,Integer> map3 = Maps.newHashMapWithExpectedSize(2);
        map3.put("zhangsan",18);
        map3.put("lisi",22);
        map3.forEach((k,v)-> System.out.println(k+" "+v));

        //有序Map
        LinkedHashMap<String,Integer> map4 = Maps.newLinkedHashMap();
        map4.put("zhangsan",18);
        map4.put("lisi",22);
        map4.put("wanger",19);
        map4.forEach((k,v)-> System.out.println(k+" "+v));
    }
结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200909161058294.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpYW5naGVjYWk1MjE3MTMxNA==,size_16,color_FFFFFF,t_70#pic_center)



你可能感兴趣的:(Guava,集合工具类,Lists,Maps,Sets)