ListUtil

Introduction

Lists are the most frequently used in collections, so a separate tool method has been encapsulated for List in the new version of Hutool.

Usage

Filtering a List

List<String> a = ListUtil.toLinkedList("1", "2", "3");
// Result: [edit1, edit2, edit3]
List<String> filter = ListUtil.filter(a, str -> "edit" + str);

Getting the positions of all elements that meet a specified rule

List<String> a = ListUtil.toLinkedList("1", "2", "3", "4", "3", "2", "1");
// [1, 5]
int[] indexArray = ListUtil.indexOfAll(a, "2"::equals);

Other methods are similar to the CollUtil tool, and many tools have duplicates as well.

Splitting

Split a collection into sections of a specified length, where each section is a separate collection, and return a list of these collections:

List<List<Object>> lists = ListUtil.split(Arrays.asList(1, 2, 3, 4), 1);
List<List<Object>> lists = ListUtil.split(null, 3);

It can also be split evenly, which means divided into N parts, with the number of each part differing by no more than 1.

// [[1, 2, 3, 4]]
List<List<Object>> lists = ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 1);

// [[1, 2], [3], [4]]
lists = ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 3);

Modify elements

We can modify elements in a collection by applying a lambda definition rule to all elements:

List<String> a = ListUtil.toLinkedList("1", "2", "3");
final List<String> filter = (List<String>) CollUtil.edit(a, str -> "edit" + str);

// "edit1"
filter.get(0);

Finding Positions

List<String> a = ListUtil.toLinkedList("1", "2", "3", "4", "3", "2", "1");

// Find the positions of all 2s
// [1, 5]
final int[] indexArray = ListUtil.indexOfAll(a, "2"::equals);

Subset Operations

final List<Integer> of = ListUtil.of(1, 2, 3, 4);

// [3, 4]
final List<Integer> sub = ListUtil.sub(of, 2, 4);

// Operations on a subset do not affect the original list
sub.remove(0);

Sorting

If we want to sort a list of beans based on the order field value, we can do the following:

@Data
@AllArgsConstructor
class TestBean {
 private int order;
 private String name;
}

final List<TestBean> beanList = ListUtil.toList(
 new TestBean(2, "test2"),
 new TestBean(1, "test1"),
 new TestBean(5, "test5"),
 new TestBean(4, "test4"),
 new TestBean(3, "test3")
 );

final List<TestBean> order = ListUtil.sortByProperty(beanList, "order");

Element Swap

List<Integer> list = Arrays.asList(7, 2, 8, 9);

// Swap element 8 with the first element
ListUtil.swapTo(list, 8, 1);

Paging

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
List<String> page = ListUtil.page(1, 2, list);

Grouping

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
List<List<String>> partition = ListUtil.partition(list, 2);