CollUtils Tutorial
This tutorial provides an overview of the CollUtils
class, which is part of the lightweight-component/aj-util
library. The CollUtils
class provides utility methods for working with collections and arrays in Java applications.
Introduction
The CollUtils
class contains static methods for common collection and array operations, including empty checks, conversions, merging, and filtering.
Main Features
- Empty/null checks for arrays, collections and maps
- Safe collection access
- Array merging and concatenation
- Collection/array conversions
- Filtering and searching collections
- Specialized int array handling
Methods
1. Empty Checks
isEmpty(Object[] array)
- Check if array is null or emptyisEmpty(Collection<?> collection)
- Check if collection is null or emptyisEmpty(Map<?, ?> map)
- Check if map is null or empty
2. Safe Access
getList(List<T> list)
- Returns empty list if input is null
3. Array Operations
printArray(Object[] arr)
- Print array contents for debuggingconcat(T[] first, T[] second)
- Concatenate two arraysaddAll(T[]... arrays)
- Merge multiple arraysnewArray(Class<?> componentType, int newSize)
- Create new empty array
4. Conversions
arrayList(E... elements)
- Convert array to ArrayListintList2Arr(List<Integer> list)
- Convert Integer list to int[]stringArr2intArr(String value)
- Convert comma-separated string to int[]
5. Filtering/Searching
findOne(List<T> list, Predicate<T> filter)
- Find first matching elementfindSome(List<T> list, Predicate<T> filter)
- Find all matching elements
Usage Examples
Empty Checks
String[] arr = null;
boolean empty = CollUtils.isEmpty(arr); // true
List<String> list = new ArrayList<>();
empty = CollUtils.isEmpty(list); // true
Safe Access
List<String> list = null;
List<String> safeList = CollUtils.getList(list); // returns empty list
Array Operations
String[] a = {"a", "b"};
String[] b = {"c", "d"};
String[] combined = CollUtils.concat(a, b); // ["a", "b", "c", "d"]
Conversions
List<String> list = CollUtils.arrayList("a", "b", "c");
List<Integer> intList = Arrays.asList(1, 2, 3);
int[] intArr = CollUtils.intList2Arr(intList); // [1, 2, 3]
int[] nums = CollUtils.stringArr2intArr("1,2,3"); // [1, 2, 3]
Filtering
List<String> names = Arrays.asList("John", "Jane", "Doe");
String result = CollUtils.findOne(names, n -> n.startsWith("J")); // "John"
List<String> allJ = CollUtils.findSome(names, n -> n.startsWith("J")); // ["John", "Jane"]
Conclusion
The CollUtils
class provides comprehensive utility methods for working with collections and arrays, making common operations more convenient and safer in Java applications.