zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Guava Lists工具类

工具 Guava lists
2023-09-11 14:15:40 时间

01 概述

GuavaGoogle 开源的一个 Java 工具库,里面有很多工具类,本文要讲的是里面的Lists工具类。

注意,使用Guava工具类库,必须先添加依赖:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.0</version>
</dependency>

02 Lists工具类

从下图可以看到Lists工具类有很多种方法:
在这里插入图片描述
下面举几个比较典型的操作演示下:

① 使用一行代码就能创建集合了,如下

  ArrayList<Student> students = Lists.newArrayList(
                new Student("张三", 33),
                new Student("李四", 40),
                new Student("王五", 23),
                new Student("赵六", 55));

② 集合间转换(Sets也是仿照Lists的),如下

HashSet<String> strHashSet = Sets.newHashSet("1", "2", "3");
ArrayList<String> strList = Lists.newArrayList(strHashSet);

③ 集合分页(虽然stream流也能做到,也看下吧),如下

ArrayList<Student> students = Lists.newArrayList(
               new Student("张三", 33),
               new Student("李四", 40),
               new Student("王五", 23),
               new Student("赵六", 55));

// 每页两条
List<List<Student>> partionStudent = Lists.partition(students, 2);

④ dto转vo时用到,如下

List<StudentVo> studentVoList = Lists.transform(studentList, new Function<Student, StudentVo>() {
    @Override
    public StudentVo apply(Student student) {
        StudentVo s = new StudentVo();
        try {
            BeanUtils.copyProperties(s, student);
        } catch (Exception e) {
        }
        s.setStudent_id(student.getId());
        s.setStudent_no(student.getStuNo());
        return s;
    }
});

03 文末

本文就举Lists用法的几个典型场景例子,不过这工具类也是有不完善之处的(例如:transform方法),各位童鞋按需使用吧。