CollStreamUtil

Introduction

One of the new features in Java 8 is Stream, and Hutool provides some wrappers for common operations.

Usage

Transforming a Collection to a Map

@Data
@AllArgsConstructor
@ToString
public static class Student {
	private long termId;//Term ID
	private long classId;//Class ID
	private long studentId;//Student ID
	private String name;//Student name
}

We can establish a map between student ID and student object:

List<Student> list = new ArrayList<>();
list.add(new Student(1, 1, 1, "Zhang San"));
list.add(new Student(1, 1, 2, "Li Si"));
list.add(new Student(1, 1, 3, "Wang Wu"));

Map<Long, Student> map = CollStreamUtil.toIdentityMap(list, Student::getStudentId);

// Zhang San's name
map.get(1L).getName();

We can also customize the keys and values of the Map, for example, we can generate a map with student ID and name:

Map<Long, String> map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName);

// Zhang San's name
map.get(1L);

Grouping by Class ID

We group students by class ID:

List<Student> list = new ArrayList<>();
list.add(new Student(1, 1, 1, "Zhang San"));
list.add(new Student(1, 2, 2, "Li Si"));
list.add(new Student(2, 1, 1, "Optimus Prime"));
list.add(new Student(2, 2, 2, "Megatron"));
list.add(new Student(2, 3, 2, "Starscream"));

Map<Long, List<Student>> map = CollStreamUtil.groupByKey(list, Student::getClassId);

Converting and Extracting Data

We can convert the student information list to a list of names:

List<String> list = CollStreamUtil.toList(null, Student::getName);

Merging Two Maps of the Same Key Type

We can merge two maps of the same key type using a custom merge lambda function to combine the values of the same key. Note that the value may be empty.

Map<Long, Student> map1 = new HashMap<>();
map1.put(1L, new Student(1, 1, 1, "Zhang San"));
Map<Long, Student> map2 = new HashMap<>();map2.put(1L, new Student(2, 1, 1,"Li Si"));```java Merge rules: ```java private String merge(Student student1, Student student2) { if (student1 == null && student2 == null) { return null; } else if (student1 == null) { return student2.getName(); } else if (student2 == null) { return student1.getName(); } else { return student1.getName() + student2.getName(); } } ```