Guava Lists 类

Guava系列之超实用的集合工具类

依赖:

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

主要方法:

各种创建list的方法
    asList()将数据组转成list
    newArrayList()
    newArrayListWithCapacity(10) 指定容量的创建
    newArrayListWithExpectedSize(20) 初始化指定容量
    newCopyOnWriteArrayList()
    newLinkedList()
partition(List list, int size) 将list按指定大小分隔成多个list
cartesianProduct(List<? extends B>… lists) 获取多个list的笛卡尔集
charactersOf(String str) 将字符串转成字符集合
reverse(List list) 反转list
transform(List fromList, Function<? super F, ? extends T> function) 数据转换

举例:

各种创建list的方法:

    @Test
    public void ListCreateTest(){
        //将数组转成list,并在开头位置插入元素
        List<String> list = Lists.asList("a",new String[]{"b","c","d"});
        List<String> list1 = Lists.asList("a","b",new String[]{"c","d","e"});

        //直接创建ArrayList
        ArrayList<String> arrayList = Lists.newArrayList();
        //创建ArrayList,并初始化
        ArrayList<String> arrayList1 = Lists.newArrayList("a","b","c");
        //基于现有的arrayList,创建一个arrayList
        ArrayList<String> arrayList2 = Lists.newArrayList(arrayList1);
        //初始化指定容量大小的ArrayList,其中容量指ArrayList底层依赖的数组的length属性值,常用于提前知道ArrayList大小的情况的初始化
        ArrayList<String> arrayList3 = Lists.newArrayListWithCapacity(10);
//创建CopyOnWriteArrayList CopyOnWriteArrayList<String> copyOnWriteArrayList = Lists.newCopyOnWriteArrayList(); //创建linkedList LinkedList<String> linkedList = Lists.newLinkedList(); }

按指定大小分隔list:

@Test
public void partitionTest(){
    List<String> list = Lists.newArrayList("a","b","c","d","e");
    //将list按大小为2分隔成多个list
    List<List<String>> splitList = Lists.partition(list,2);
    System.out.println(splitList);
}

输出:

[[a, b], [c, d], [e]]

字符串转成字符集合:

@Test
public void partitionTest(){
    ImmutableList<Character> list = Lists.charactersOf("ababcdfb");
    System.out.println(list);
}

输出:

[a, b, a, b, c, d, f, b]

list反转

@Test
public void partitionTest(){
    List<String> list = Lists.newArrayList("a","b","c","1","2","3");
    //反转list
    List<String> reverseList = Lists.reverse(list);
    System.out.println(reverseList);
}

输出:

[3, 2, 1, c, b, a]

  

 

更多方法:https://blog.csdn.net/pzjtian/article/details/106739606

  

 

上一篇:Guava - 拯救垃圾代码,写出优雅高效,效率提升N倍!


下一篇:Ubuntu系统中多个版本的程序指定默认版本