谷歌团队推荐的Java工具集Guava使用示例2

上一篇,Guava Demo1 示例

一、List操作

1.1 不可变集合ImmutableList

public class ImmutableList_ {

    public static <T> void iList(List<T> list) {
        ImmutableList<T> immutableList = ImmutableList.copyOf(list);
        System.out.println(immutableList);
    }

    public static void iList() {
        ImmutableList<String> immutableList = ImmutableList.of("Geeks", "For", "Geeks");
        System.out.println(immutableList);
    }

    @Test
    public void t1() {
        List<String> list = Lists.newArrayList("Geeks", "For", "Geeks");
        iList(list);
        iList();
    }

    @Test
    public void t2() {
        List<String> list = Lists.newArrayList("Geeks", "For", "Geeks");
        ImmutableList<String> iList = ImmutableList.<String>builder()
                .addAll(list)
                .add("Computer", "Portal")
                .build();
        System.out.println(iList);
    }

    @Test
    public void t3() {
        List<String> list = new ArrayList<>();
        list.add("Geeks");
        ImmutableList<String> iList = ImmutableList.copyOf(list);
        System.out.println(iList);
    }
}

1.2 List常见操作

public class List_Ope {

    private static List<Per> list;

    static
    {
        LocalDateTime now = LocalDateTime.now();
        Per p1 = new Per().setPerId(1l).setAge(12).setName("tets").setBirth(now.minusDays(50)).setDeath(now.plusMonths(378));
        Per p2 = new Per().setPerId(2l).setAge(28).setName("tets2").setBirth(now.minusDays(25)).setDeath(now.plusMonths(358));
        Per p3 = new Per().setPerId(3l).setAge(25).setName("tets3").setBirth(now.minusDays(27)).setDeath(now.plusMonths(338));
        Per p4 = new Per().setPerId(4l).setAge(14).setName("tets4").setBirth(now.minusDays(37)).setDeath(now.plusMonths(348));
        list = Lists.newArrayList(p1,p2,p3,p4);
    }

    /**
     * 这里只能去除null,无法空串
     */
    @Test
    public void t1(){
        List<String> names = Lists.newArrayList("","  ","John", null, "Adam", null, "Jane","");
        Iterables.removeIf(names, Predicates.isNull());
        names.forEach(System.out::println);
    }

    /**
     * list过滤
     */
    @Test
    public void t2(){
        List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
        Iterable<String> result = Iterables.filter(names, Predicates.containsPattern("a"));
        result.forEach(System.out::println);
    }
    // 包含"J",或者不包括"a"
    @Test
    public void t21(){
        List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
        Iterable<String> result = Iterables.filter(names, Predicates.or(Predicates.containsPattern("J"), Predicates.not(Predicates.containsPattern("a"))));
        result.forEach(System.out::println);
    }
    //
    @Test
    public void t3(){
        List<Per> pers = Lists.newArrayList(list);
        list.forEach(e ->{
            if (e.getAge()>15) {
                pers.remove(e);
            }
        });
        pers.forEach(System.out::println);
    }
    // java8 stream 过滤
    @Test
    public void t4(){
        final List<Per> list1 = list.stream().filter(e -> e.getAge() > 20).collect(Collectors.toList());
        list1.forEach(System.out::println);
    }

    // guava  过滤
    @Test
    public void t5(){
        final Iterable<Per> filter = Iterables.filter(list, Predicates.notNull());
        filter.forEach(System.out::println);
    }
}

1.3 List_Partition操作

public class List_Partition {
    /**
     * 对List切分子List,数字
     */
    @Test
    public void t1() {
        List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        List<List<Integer>> lists
                = Lists.partition(myList, 2);
        for (List<Integer> sublist : lists)
            System.out.println(sublist);
    }
    @Test
    public void t2() {
        List<Character> myList = Arrays.asList('H', 'E', 'L', 'L', 'O', 'G', 'E', 'E', 'K', 'S');
        List<List<Character>> lists
                = Lists.partition(myList, 3);
        for (List<Character> sublist : lists)
            System.out.println(sublist);
    }
}

1.4 Lists_reverse操作

public class Lists_reverse {

    /**
     * 逆序输出
     */
    @Test
    public void t1(){
        List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> reverse = Lists.reverse(myList);
        System.out.println(reverse);
    }
}

二、Set操作

2.1 Sets_diff

public class Sets_diff {
    /**
     * 计算两个List差集,注意A,B集合的差集是不同的
     */
    @Test
    public void t1() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6);
        Set<Integer> set2 = Sets.newHashSet(1, 2, 3, 5, 7);
        Set<Integer> diff1 = Sets.difference(set1, set2);
        Set<Integer> diff2 = Sets.difference(set2, set1);
        System.out.println("Sets.difference(set1, set2):" + diff1); // 4,6
        System.out.println("Sets.difference(set2, set1):" + diff2); // 7
    }

    @Test
    public void t2() {
        Set<String> set1 = Sets.newHashSet("H", "E", "L", "L", "O", "G");
        Set<String> set2 = Sets.newHashSet("L", "I", "K", "E", "G");

        Set<String> diff1 = Sets.difference(set1, set2);
        Set<String> diff2 = Sets.difference(set2, set1);
        System.out.println("Sets.difference(set1, set2):" + diff1); //H,O
        System.out.println("Sets.difference(set2, set1)" + diff2); // I,K

    }
}

2.2 Sets_intersection

public class Sets_intersection {

    /**
     * Sets取交集,List没有,List里面有重复的元素
     */
    @Test
    public void t1(){
        Set<Integer> set1 = Sets.newHashSet(10, 20, 30, 40, 50);
        Set<Integer> set2 = Sets.newHashSet(30, 50, 70, 90);

        Set<Integer> answer = Sets.intersection(set1, set2);
        System.out.println("Set 1 intersection Set 2: " + answer);
    }
    @Test
    public void t2(){
        Set<String> set1 = Sets.newHashSet("G", "e", "e", "k", "s"); // 这里会自动除重
        Set<String> set2 = Sets.newHashSet("g", "f", "G", "e");

        Set<String> answer = Sets.intersection(set1, set2);
        System.out.println("Set 1 intersection Set 2: " + answer);
    }

}

2.3 Sets_union

public class Sets_union {
    @Test
    public void t1(){
        Set<Integer> set1 = Sets.newHashSet(5,8,3,6,9);
        Set<Integer> set2 = Sets.newHashSet(3, 5, 7, 9);

        Set<Integer> answer = Sets.union(set1, set2);
        Set<Integer> answer2 = Sets.union(set2, set1);

        System.out.println("Set 1 : " + set1);
        System.out.println("Set 1 union Set 2: " + answer);
        System.out.println("Set 2 union Set 1: " + answer2);
    }

}

三、Optional操作

public class Optional_ {
    @Test
    public void t1(){
        // 初始化 List
        List<String> myList = new ArrayList<>();
        myList.add("Geeks");
        myList.add("for");
        myList.add("GeeksClasses");
        myList.add(null);
        myList.add("GeeksforGeeks");
        myList.add("");
        myList.add("Data Structures");

        displayValuesUsingJavaNulls(myList); // 基础手写方法判断是否为空代码
        displayValuesUsingGuavaOptional(myList); // 调用 guava Optional封装方法实现
    }

    // Method to display values using Java Nulls
    public static void displayValuesUsingJavaNulls(List<String> myList) {
        System.out.println("Displaying values using Java Nulls");
        // For every String in myList
        for (String str : myList) {
            if (str == null || str.isEmpty()) {
                System.out.println("String : Value is empty or not available");
            }
            else {
                System.out.println("String : " + str);
            }
        }
        System.out.println();
    }

    // 使用 Guava Optional处理
    public static void displayValuesUsingGuavaOptional(List<String> myList) {
        System.out.println("Displaying values using Guava Optional");

        for (String str : myList) {
            Optional<String> optionalName = Optional.fromNullable(emptyToNull(str));
            System.out.println("String : " + optionalName.or("String : Value is empty or not available"));
        }
    }
}

四、Split操作

public class Split_toList {

    /**
     * 将string 按照 ','切割成List数组
     */
    @Test
    public void t1(){
        String str = "Hello, geeks, for, geeks, noida";
        List<String> myList = Splitter.on(',').splitToList(str);
        for (String temp : myList) {
            System.out.println(temp);
        }
    }

    /**
     * 不可以连续切,只匹配后面的 on()
     */
    @Test
    public void t2(){
        String str = "Everyone. should. Learn, Data. Structures";
        List<String> myList = Splitter.on('.').on(',').splitToList(str);
        for (String temp : myList) {
            System.out.println(temp);
        }
    }

    /**
     * 对分割符前后的空格或者为空时的处理
     */
    @Test
    public void t3(){
        String str = "  , Everyon  ,  , should,  Learn, Data, Structures";
        List<String> guaList = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(str);
        for (String temp : guaList) {
            System.out.println(temp);
        }
    }
}

五、Table操作

public class Table_ {
    @Test
    public void t1(){

       Table<String, String, String> studentTable = HashBasedTable.create();
        studentTable.put("CSE", "5", "Dhiman");
        studentTable.put("CSE", "7", "Shubham");
        studentTable.put("CSE", "9", "Abhishek");
        studentTable.put("CSE", "12", "Sahil");

        studentTable.put("ECE", "15", "Ram");
        studentTable.put("ECE", "18", "Anmol");
        studentTable.put("ECE", "20", "Akhil");
        studentTable.put("ECE", "25", "Amrit");

        Map<String, String> eceMap = studentTable.row("ECE");
        System.out.println("List of ECE students : ");

        for (Map.Entry<String, String> student : eceMap.entrySet()) {
            System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue());
        }

        System.out.println();

        Map<String, String> stuMap = studentTable.column("12");
        for (Map.Entry<String, String> student : stuMap.entrySet()) {
            System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue());
        }
    }

}

这里是更多关于关于Guava定义的Collections,JDK中没有的

全部评论

相关推荐

粗心的雪碧不放弃:纯学历问题,我这几个月也是一直优化自己的简历,后来发现优化到我自己都觉得牛逼的时候,发现面试数量也没有提升,真就纯学历问题
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务