0
# Collection Utilities
1
2
Comprehensive collection manipulation utilities through `CollUtil`, `ListUtil`, `SetUtil`, and `MapUtil` classes, providing creation, filtering, transformation, and analysis operations.
3
4
## Import
5
6
```java
7
import cn.hutool.core.collection.CollUtil;
8
import cn.hutool.core.collection.ListUtil;
9
import cn.hutool.core.collection.SetUtil;
10
import cn.hutool.core.map.MapUtil;
11
import cn.hutool.core.util.IterUtil;
12
```
13
14
## Collection Creation
15
16
### List Creation
17
18
```java { .api }
19
// Create lists
20
public static <T> List<T> newArrayList();
21
public static <T> List<T> newArrayList(T... values);
22
public static <T> List<T> newArrayList(Collection<T> collection);
23
public static <T> List<T> newArrayList(Iterable<T> iterable);
24
25
// Create with capacity
26
public static <T> List<T> newArrayList(int initialCapacity);
27
28
// Create other list types
29
public static <T> LinkedList<T> newLinkedList();
30
public static <T> LinkedList<T> newLinkedList(T... values);
31
```
32
33
### Set Creation
34
35
```java { .api }
36
// Create sets
37
public static <T> Set<T> newHashSet();
38
public static <T> Set<T> newHashSet(T... values);
39
public static <T> Set<T> newHashSet(Collection<T> collection);
40
41
// Create other set types
42
public static <T> LinkedHashSet<T> newLinkedHashSet();
43
public static <T> TreeSet<T> newTreeSet();
44
```
45
46
### Map Creation
47
48
```java { .api }
49
// Create maps
50
public static <K, V> Map<K, V> newHashMap();
51
public static <K, V> Map<K, V> newHashMap(int size, boolean isOrder);
52
53
// Create with initial data
54
public static <K, V> Map<K, V> of(K key, V value);
55
public static <K, V> Map<K, V> of(K key1, V value1, K key2, V value2);
56
// ... more overloads for up to 5 key-value pairs
57
58
// Builder pattern
59
public static <K, V> MapBuilder<K, V> builder();
60
public static <K, V> MapBuilder<K, V> builder(Map<K, V> map);
61
62
// Create other map types
63
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap();
64
public static <K, V> TreeMap<K, V> newTreeMap();
65
public static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap();
66
```
67
68
**Usage Examples:**
69
70
```java
71
// Create collections with initial data
72
List<String> names = CollUtil.newArrayList("Alice", "Bob", "Charlie");
73
Set<Integer> numbers = CollUtil.newHashSet(1, 2, 3, 4, 5);
74
Map<String, Integer> scores = MapUtil.of(
75
"Alice", 85,
76
"Bob", 92,
77
"Charlie", 78
78
);
79
80
// Builder pattern for maps
81
Map<String, Object> config = MapUtil.builder(new HashMap<String, Object>())
82
.put("timeout", 5000)
83
.put("retries", 3)
84
.put("debug", true)
85
.build();
86
```
87
88
## Collection Validation
89
90
### Empty and Null Checks
91
92
```java { .api }
93
// Check if empty
94
public static boolean isEmpty(Collection<?> collection);
95
public static boolean isNotEmpty(Collection<?> collection);
96
97
// Check if empty for maps
98
public static boolean isEmpty(Map<?, ?> map);
99
public static boolean isNotEmpty(Map<?, ?> map);
100
101
// Check if empty for iterables
102
public static boolean isEmpty(Iterable<?> iterable);
103
```
104
105
### Size Operations
106
107
```java { .api }
108
// Get size safely
109
public static int size(Collection<?> collection);
110
public static int size(Map<?, ?> map);
111
public static int size(Iterable<?> iterable);
112
113
// Check size conditions
114
public static boolean hasItem(Iterable<?> iterable);
115
```
116
117
## Collection Manipulation
118
119
### Adding and Removing Elements
120
121
```java { .api }
122
// Add elements safely
123
public static <T> List<T> addAll(Collection<T> coll, T... elements);
124
public static <T> List<T> addAll(Collection<T> coll, Iterable<T> iterable);
125
126
// Remove elements
127
public static <T> boolean removeAny(Collection<T> coll, T... elements);
128
public static <T> boolean removeAll(Collection<T> coll, Collection<T> elements);
129
130
// Clear collections safely
131
public static void clear(Collection<?>... collections);
132
```
133
134
### Collection Conversion
135
136
```java { .api }
137
// Convert between collection types
138
public static <T> List<T> toList(Iterable<T> iterable);
139
public static <T> Set<T> toSet(Iterable<T> iterable);
140
141
// Convert arrays
142
public static <T> List<T> toList(T[] array);
143
public static <T> Set<T> toSet(T[] array);
144
145
// Convert with mapping
146
public static <T, R> List<R> map(Iterable<T> iterable, Function<T, R> mapper);
147
public static <T, R> Set<R> mapToSet(Iterable<T> iterable, Function<T, R> mapper);
148
```
149
150
## Filtering and Searching
151
152
### Filtering Operations
153
154
```java { .api }
155
// Filter collections
156
public static <T> List<T> filter(Collection<T> collection, Predicate<T> predicate);
157
public static <T> List<T> filterNew(Collection<T> collection, Filter<T> filter);
158
159
// Find operations
160
public static <T> T findOne(Iterable<T> collection, Predicate<T> predicate);
161
public static <T> int findIndex(Collection<T> collection, Predicate<T> predicate);
162
163
// Check conditions
164
public static <T> boolean contains(Collection<T> collection, T value);
165
public static <T> boolean containsAny(Collection<T> collection1, Collection<T> collection2);
166
public static <T> boolean containsAll(Collection<T> collection1, Collection<T> collection2);
167
```
168
169
### Collection Matching
170
171
```java { .api }
172
// Match operations
173
public static <T> boolean allMatch(Iterable<T> iterable, Predicate<T> predicate);
174
public static <T> boolean anyMatch(Iterable<T> iterable, Predicate<T> predicate);
175
public static <T> boolean noneMatch(Iterable<T> iterable, Predicate<T> predicate);
176
```
177
178
**Usage Examples:**
179
180
```java
181
List<User> users = getUserList();
182
183
// Filter active users
184
List<User> activeUsers = CollUtil.filter(users, User::isActive);
185
186
// Find first admin user
187
User admin = CollUtil.findOne(users, user -> "admin".equals(user.getRole()));
188
189
// Check if any user is under 18
190
boolean hasMinors = CollUtil.anyMatch(users, user -> user.getAge() < 18);
191
192
// Get user names
193
List<String> names = CollUtil.map(users, User::getName);
194
```
195
196
## Set Operations
197
198
### Set Mathematics
199
200
```java { .api }
201
// Union, intersection, difference
202
public static <T> Set<T> union(Collection<T> coll1, Collection<T> coll2);
203
public static <T> Set<T> intersection(Collection<T> coll1, Collection<T> coll2);
204
public static <T> Set<T> difference(Collection<T> coll1, Collection<T> coll2);
205
206
// Disjoint check
207
public static boolean disjoint(Collection<?> coll1, Collection<?> coll2);
208
```
209
210
**Usage Examples:**
211
212
```java
213
Set<String> set1 = CollUtil.newHashSet("A", "B", "C");
214
Set<String> set2 = CollUtil.newHashSet("B", "C", "D");
215
216
Set<String> unionSet = CollUtil.union(set1, set2); // [A, B, C, D]
217
Set<String> intersect = CollUtil.intersection(set1, set2); // [B, C]
218
Set<String> diff = CollUtil.difference(set1, set2); // [A]
219
```
220
221
## Map Operations
222
223
### Map Utilities
224
225
```java { .api }
226
// Get values safely
227
public static <K, V> V get(Map<K, V> map, K key, V defaultValue);
228
public static <K, V> V get(Map<K, V> map, K key, Supplier<V> defaultSupplier);
229
230
// Put operations
231
public static <K, V> V putIfAbsent(Map<K, V> map, K key, V value);
232
public static <K, V> Map<K, V> putAll(Map<K, V> map, Map<K, V> otherMap);
233
234
// Remove operations
235
public static <K, V> V removeAny(Map<K, V> map, K... keys);
236
237
// Check operations
238
public static boolean isEmpty(Map<?, ?> map);
239
public static boolean isNotEmpty(Map<?, ?> map);
240
```
241
242
### Map Transformation
243
244
```java { .api }
245
// Reverse map (swap keys and values)
246
public static <K, V> Map<V, K> reverse(Map<K, V> map);
247
248
// Filter maps
249
public static <K, V> Map<K, V> filter(Map<K, V> map, Predicate<Entry<K, V>> predicate);
250
251
// Transform maps
252
public static <K, V, R> Map<K, R> transformValue(Map<K, V> map, Function<V, R> transformer);
253
public static <K, V, R> Map<R, V> transformKey(Map<K, V> map, Function<K, R> transformer);
254
```
255
256
### MapBuilder Class
257
258
```java { .api }
259
public class MapBuilder<K, V> {
260
// Add entries
261
public MapBuilder<K, V> put(K key, V value);
262
public MapBuilder<K, V> putAll(Map<K, V> map);
263
264
// Conditional puts
265
public MapBuilder<K, V> putIfAbsent(K key, V value);
266
public MapBuilder<K, V> putIfNotNull(K key, V value);
267
268
// Build result
269
public Map<K, V> build();
270
}
271
```
272
273
**Usage Examples:**
274
275
```java
276
Map<String, Object> userMap = MapUtil.builder(new HashMap<String, Object>())
277
.put("id", 1)
278
.put("name", "John")
279
.putIfNotNull("email", user.getEmail())
280
.build();
281
282
// Safe get with default
283
String role = MapUtil.get(userMap, "role", "user");
284
285
// Transform map values
286
Map<String, String> upperNames = MapUtil.transformValue(nameMap, String::toUpperCase);
287
```
288
289
## Iterator Utilities
290
291
### Iterator Operations
292
293
```java { .api }
294
// Check if empty
295
public static boolean isEmpty(Iterator<?> iterator);
296
public static boolean hasNext(Iterator<?> iterator);
297
298
// Get elements
299
public static <T> T getFirst(Iterable<T> iterable);
300
public static <T> T getLast(Iterable<T> iterable);
301
public static <T> T get(Iterable<T> iterable, int index);
302
303
// Convert to collections
304
public static <T> List<T> toList(Iterator<T> iterator);
305
public static <T> Set<T> toSet(Iterator<T> iterator);
306
307
// Join elements
308
public static <T> String join(Iterator<T> iterator, CharSequence delimiter);
309
public static <T> String join(Iterable<T> iterable, CharSequence delimiter);
310
```
311
312
## Pagination and Slicing
313
314
### List Pagination
315
316
```java { .api }
317
// Paginate lists
318
public static <T> List<List<T>> split(List<T> list, int size);
319
public static <T> List<T> sub(List<T> list, int start, int end);
320
public static <T> List<T> page(List<T> list, int pageNo, int pageSize);
321
```
322
323
**Usage Examples:**
324
325
```java
326
List<Integer> numbers = CollUtil.range(1, 100); // [1, 2, 3, ..., 100]
327
328
// Split into chunks of 10
329
List<List<Integer>> chunks = CollUtil.split(numbers, 10);
330
331
// Get page 3 with 20 items per page
332
List<Integer> page3 = CollUtil.page(numbers, 3, 20); // [41, 42, ..., 60]
333
334
// Get sublist
335
List<Integer> subset = CollUtil.sub(numbers, 10, 20); // [11, 12, ..., 20]
336
```
337
338
## Collection Generation
339
340
### Range and Sequence Generation
341
342
```java { .api }
343
// Generate number ranges
344
public static List<Integer> range(int stop);
345
public static List<Integer> range(int start, int stop);
346
public static List<Integer> range(int start, int stop, int step);
347
348
// Generate repeated elements
349
public static <T> List<T> repeat(T element, int count);
350
```
351
352
**Usage Examples:**
353
354
```java
355
// Generate ranges
356
List<Integer> oneToTen = CollUtil.range(1, 11); // [1, 2, 3, ..., 10]
357
List<Integer> evens = CollUtil.range(2, 21, 2); // [2, 4, 6, ..., 20]
358
359
// Repeat elements
360
List<String> dots = CollUtil.repeat(".", 5); // [".", ".", ".", ".", "."]
361
```
362
363
All collection utilities are null-safe and handle edge cases gracefully. They provide consistent behavior across different collection types and offer both mutable and immutable operation variants where appropriate.