Guava Lists工具类

简介: Guava Lists工具类

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

目录
相关文章
|
9月前
|
缓存 Java
【JAVA】基于Guava实现本地缓存
【JAVA】基于Guava实现本地缓存
135 0
|
存储 设计模式 缓存
Java源码分析:Guava之不可变集合ImmutableMap的源码分析
Java源码分析:Guava之不可变集合ImmutableMap的源码分析
73 0
|
9月前
|
缓存 安全 Java
Google guava工具类的介绍和使用
Google guava工具类的介绍和使用
251 1
【JavaSE】Collections集合工具类专题(上)
文章目录 1 Collections 工具类常用方法 1.1 排序反转类 1.1.1 reverse() 1.1.2 shuffle() 1.1.3 sort() 1.2 查找、替换类 1.2.1 Object max() 1.2.2 frequency() 1.2.3 copy() 1.2.4 replaceAll()
【JavaSE】Collections集合工具类专题(上)
【JavaSE】Collections集合工具类专题(下)
文章目录 1 Collections 工具类常用方法 1.1 排序反转类 1.1.1 reverse() 1.1.2 shuffle() 1.1.3 sort() 1.2 查找、替换类 1.2.1 Object max() 1.2.2 frequency() 1.2.3 copy() 1.2.4 replaceAll()
【JavaSE】Collections集合工具类专题(下)
|
安全 Java Maven
Guava 如何让 Map 不可变之 ImmutableMap
Guava 如何让 Map 不可变之 ImmutableMap
456 0
Guava 如何让 Map 不可变之 ImmutableMap
|
存储 缓存 Java
Guava中这些Map的骚操作,让我的代码量减少了50%
Guava是google公司开发的一款Java类库扩展工具包,内含了丰富的API,涵盖了集合、缓存、并发、I/O等多个方面。使用这些API一方面可以简化我们代码,使代码更为优雅,另一方面它补充了很多jdk中没有的功能,能让我们开发中更为高效。
200 0
|
Java API
Guava - Maps.newHashMap 和 new HashMap 区别
Guava - Maps.newHashMap 和 new HashMap 区别
1110 0
|
Java
Guava-Objects使用
Java中的Object提供了很多方法供所有的类使用,特别是toString、hashCode、equals、getClass等方法,在日常开发中作用很大,Guava中包含Objects类,其提供了很多更为强大的方法。
141 0
|
存储
guava学习:guava集合类型-Bimap
学习guava让我惊喜的第二个接口就是:Bimap BiMap是一种特殊的映射其保持映射,同时确保没有重复的值是存在于该映射和一个值可以安全地用于获取键背面的倒数映射。 最近开发过程中,经常会有这种根据key找value或者根据value找key 的功能,之前都是将值存储到枚举或者map中,然后通过反转的写法来实现的,直到发现了Bimap,才发现原来还有这么简便的方式。
1253 0