ListUtil工具类常用方法

工具类ListUtil常用方法

我们在对集合进行某些操作时候,工具类往往会更加方便上手,我列一些常用的以便大家互相学习

引入所需依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

差集(subtract)

案列:

List<Integer> a = Arrays.asList(1, 2, 3, 4);
List<Integer> b = Arrays.asList(2, 3, 4, 5);
// subract 差集 (a中有而b中没有的)
System.out.println(ListUtils.subtract(a,b)); // [1]
System.out.println(ListUtils.subtract(b,a)); // [5]

并集(union)

案例:

List<Integer> a = Arrays.asList(1, 2, 3, 4);
List<Integer> b = Arrays.asList(2, 3, 4, 5);
System.out.println(ListUtils.union(a,b));//[1,2,3,4,2,3,4,5]

交集(intersection)

List<Integer> a = Arrays.asList(1, 2, 3, 4);
List<Integer> b = Arrays.asList(2, 3, 4, 5);
System.out.println(ListUtils.intersection(a,b));//[2,3,4]

去除 (removeAll)

List<Integer> a = Arrays.asList(1, 2, 3, 4);
List<Integer> c = Arrays.asList(1, 2, 3, 4,5,6,7);
System.out.println(ListUtils.removeAll(c,a));//[5,6,7]

拆分(partition)

List<Integer> c = Arrays.asList(1, 2, 3, 4,5,6,7);
System.out.println(ListUtils.partition(c,2));//[1,2],[3,4],[5,6],[7]
posted @ 2022-11-09 17:28  JamieChyi  阅读(85)  评论(0)    收藏  举报  来源