常用的Java工具类之Guava使用

1,478 阅读2分钟

Guava为集合类提供相关工具类以及一些集合的新类型,加快我们日常开发效率。

Guava工具类的引入

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

集合新工具类-Lists

List实现类介绍

常用的List集合有ArrayList、Vector和LinkedList。

ArrayList和Vector都是使用数组方式存储数据,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据库而插入数据慢,Vector中的方法中添加了synchronized修饰,因此Vector是线程安全的容器,但性能上比ArrayList差。

LinkedList使用双向链表实现存储(将内存中零散的内存单元通过附加的引用关联起来,形成一个可以按序号索引的线性结构,这种链式存储方式与数组的连续存储方式相比,内存的利用率更高),按序号索引数据需要进行前向或后向遍历,但是插入数据时只需要记录本项的前后项即可,插入数据较快。

总结
  1. ArrayList是实现了基于动态数组的数据结构,LinkedList是基于链表的数据结构。
  2. 对于随机访问get和set,ArrayList要优于LinkedList,因为LinkedList要移动指针。
  3. 对于新增和删除操作,即add和remove操作,LinkedList速度较快,因为ArrayList要移动数据。

Lists.newArrayList()

ArrayList<String> list2 = Lists.newArrayList();
LinkedList<Object> list3 = Lists.newLinkedList();
//如果需要指定初始大小
List<String> list = Lists.newArrayListWithCapacity(100);

Lists.partition()

Lists.partition()方法是按照指定大小拆分大集合

        //指定初始大小为100
        List<String> list = Lists.newArrayListWithCapacity(100);
        //把list集合按照一组10个拆分成更小的集合
        List<List<String>> smallList = Lists.partition(list, 10);

        for (int i = 0; i < 100; i++) {
            list.add(i + "");
        }
        smallList.forEach(System.out::println);

输出结果为:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

这适用于大量数据批量处理的情况,比如批量插入数据,一次插入10W条数据,这种大量数据出错的话,不容易排查和回滚,因此可以拆分为1000条数据。