Guava中的常见集合操作用法

      本文主要介绍Guava中几种处理字符串Map方法,包括Joiner(连接)FluentIterable(过滤、转换集合)和Splitter(分割)。本文基于Java 8进行测试,Guava 版本为 

dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>29.0-jre</version>
</dependency>

 Joiner

      我们来看看下面经常遇见的一个案例:定义包含如下元素的一个列表,请按照英文逗号分割,并过滤掉值null元素  

"a", null, "b", "g", "8", "9"

    用JDK中的方法实现方案如下: 

@Test
    public void joinerListByJdkTest() {
        List<String> lists = Lists.newArrayList("a", null, "b", "g", "8", "9");
        StringBuilder sb = new StringBuilder();
        for (Object item : lists) {
            if (item != null) {
                sb.append(item)
                   .append(DELIMITER);
            }
        }
        LOGGER.info(sb.substring(0, sb.length() - DELIMITER.length()));
    }

       执行结果:a,b,g,8,9。 

      是不是很简单,但是繁琐?例如for循环执行结束之后必须修正字符串末尾分隔符:sb.substring(0, sb.length() - DELIMITER.length());Guava版本呢? 

@Test
    public void joinerListByGuavaTest() {
        List<String> lists = Lists.newArrayList("a", null, "b", "g", "8", "9");
        String result = Joiner.on(DELIMITER).skipNulls().join(lists);
        LOGGER.info(result);
    }

   我们不再考虑更多的细节,并且很有语义的告诉代码的阅读者用什么分隔符分隔,需要过滤null值再join 

      关于Map对象的连接,Guava提供withKeyValueSeparator用于指定键值对直接的分隔符 

    /**
     * joiner withKeyValueSeparator(String keyValueSeparator)   map连接器,keyValueSeparator为key和value之间的分隔符
     * <p>
     * 结果:
     * 1:哈哈,2:压压
     */
    @Test
    public void withMapTest() {
        Map<Integer, String> maps = Maps.newHashMap();
        maps.put(1, "哈哈");
        maps.put(2, "压压");
        String result = Joiner.on(DELIMITER).withKeyValueSeparator(":").join(maps);
        System.out.println(result);
    }

  

FluentIterable

  转换(transform)集合类型,transform接收Function接口,一般在方法中采用new接口实现回调方法apply的方式。

      FluentIterable guava集合类中常用的一个类,主要用于过滤、转换集合中的数据;它是一个抽象类,实现了Iterable接口,大多数方法都返回FluentIterable对象,这也是guava的思想之一。下面主要针对filter transform方法进行演示。filter方法要接收Predicate接口,transform接收Function接口。

      Filter的应用实例:

    /**
     * 过滤出年龄大于20岁的学生
     * <p>
     * 这里有一个潜在的坑,在高版本(21.0++)的guava中Predicate接口继承了java 8中的java.util.function.Predicate
     *
     * @param students
     */
    public static void filterStudents(List<Student> students) {
        FluentIterable<Student> filter = FluentIterable.from(students).filter(
                new Predicate<Student>() {
                    @Override
                    public boolean apply(Student student) {
                        return Integer.valueOf(student.getAge()) > 20;
                    }
                });
        for (Student student : filter) {
            System.out.println(student);
        }
    }

      transform三种类型的应用:

    private void myTest(List<Student> students) {
        FluentIterable<String> transform = (FluentIterable<String>) FluentIterable.from(students).transform(
                new Function<Student, String>() {
                    @Override
                    public String apply(Student user) {
                        // 以分隔符#分隔姓名和年龄
                        return Joiner.on("#").join(user.getName(), user.getAge());
                    }
                });
        for (String user : transform) {
            System.out.println(user);
        }
    }

    /**
     * 返回格式化后的列表
     */
    private void myTestList(List<Student> students) {
        // 直接返回 List 类型对象
        List<String> transform = FluentIterable.from(students).transform(
                new Function<Student, String>() {
                    @Override
                    public String apply(Student user) {
                        return Joiner.on("=").join(user.getName(), user.getAge());
                    }
                }).toList();
        System.out.println(transform);
    }

    /**
     * 定制特殊格式,并返回合并后的字符串
     * 这里有一个潜在的坑,在版本 18.0才可以使用 .join(Joiner.on("、"))
     * @param students
     */
    private void givenFormater(List<Student> students) {
        String result = FluentIterable.from(students).transform(new Function<Student, String>() {
            @Override
            public String apply(Student user) {
                // 通过特殊格式定制字符串
                return user.getName() + "(" + user.getAge() + ")";
            }
            // 指定各个字符串之间的分隔符
        }).join(Joiner.on("、"));

        System.out.println(result);
}
    @Test
    public void guavaStudy() {
        List<Student> students = new ArrayList<>();
        Student student = new Student();
        student.setName("Lucy");
        student.setAge("19");
        students.add(student);
        students.add(new Student("Wiener", "32", "河南商丘"));
        students.add(new Student("East7", "21"));

        myTest(students);
        LOGGER.info("----- givenFormater ------");
        givenFormater(students);
        myTestList(students);
        LOGGER.info("----- filterStudents ------");
        filterStudents(students);
    }

      函数givenFormater比较特殊,其执行结果如下

Lucy(19)、Wiener(32)、East7(21)

      可以看到,其定制结果集格式的功能非常强悍。

Splitter

      Splitter可以对字符串进行分割,其分割的方式有两种——按字符/字符串分割和按正则进行分割,下面分析按字符分隔

   /**
    * on 按照指定分隔符分隔字符串
    * 结果:[  河南商丘, 767, 32, , 哈哈 ]
    */
    @Test
    public void splitterListTest() {
        String test = "  河南商丘,767,32,,哈哈 ";
        List<String> lists = Splitter.on(DELIMITER).splitToList(test);
        System.out.println(lists);
    }
    /**
     * trimResults 拆分并且去除元素前后空格
     * <p>
     * 结果:[河南商丘, 767, 32, , 哈哈]
     */
    @Test
    public void trimResultListTest() {
        String test = "  河南商丘,767,32,,哈哈 ";
        List<String> lists = Splitter.on(DELIMITER).trimResults().splitToList(test);
        System.out.println(lists);
    }

    /**
     * omitEmptyStrings 去除拆分后的、空的字符串
     * <p>
     * 结果:[河南商丘, 767, 32, 哈哈]
     */
    @Test
    public void omitEmptyStringsTest() {
        String test = "  河南商丘,767,32,,哈哈 ";
        List<String> lists = Splitter.on(DELIMITER).omitEmptyStrings().trimResults().splitToList(test);
        System.out.println(lists);
    }

Reference

https://www.cnblogs.com/whitewolf/p/4214749.html

猜你喜欢

转载自www.cnblogs.com/east7/p/12897273.html