文章目录


01 概述

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

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

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

02 Lists工具类

从下图可以看到​​Lists​​工具类有很多种方法:

Guava 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​​方法),各位童鞋按需使用吧。