Skip to content

常用工具类

你有没有写过这种代码?

java
if (str != null && !str.equals("") && !str.trim().isEmpty()) {
    // 使用 str
}

每次都要写这么长,累不累?

其实 JDK 和一些常用库已经提供了丰富的工具方法,用好了事半功倍。

Collections:集合操作百宝箱

排序与查找

java
public class CollectionsSortSearch {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6));

        // 排序
        Collections.sort(list);
        System.out.println("升序: " + list);  // [1, 1, 2, 3, 4, 5, 6, 9]

        // 降序排序
        Collections.sort(list, Collections.reverseOrder());
        System.out.println("降序: " + list);  // [9, 6, 5, 4, 3, 2, 1, 1]

        // 二分查找(必须先排序!)
        int index = Collections.binarySearch(list, 4);
        System.out.println("4 的位置: " + index);  // 4

        // 未找到返回负数
        int notFound = Collections.binarySearch(list, 100);
        System.out.println("100 不在: " + notFound);  // 负数
    }
}

最大最小值

java
public class MinMaxDemo {

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(3, 1, 4, 1, 5, 9);

        // 最大最小值
        System.out.println("最大值: " + Collections.max(nums));      // 9
        System.out.println("最小值: " + Collections.min(nums));      // 1

        // 自定义比较器
        System.out.println("最短字符串: " + Collections.max(
            Arrays.asList("aa", "a", "aaa"),
            Comparator.comparingInt(String::length)
        ));  // "a"
    }
}

不可变集合

java
public class ImmutableCollections {

    public static void main(String[] args) {
        // 单元素集合
        List<String> singleton = Collections.singletonList("only");
        Set<Integer> singletonSet = Collections.singleton(42);

        // 空集合
        List<Object> emptyList = Collections.emptyList();
        Set<String> emptySet = Collections.emptySet();
        Map<String, Integer> emptyMap = Collections.emptyMap();

        // 注意:不可变集合调用 add/remove 会抛 UnsupportedOperationException
        // singleton.add("new");  // ❌ 运行时异常

        // JDK 9+ 推荐用 List.of / Set.of / Map.of
        List<String> jdk9List = List.of("a", "b", "c");
        // jdk9List.add("d");  // ❌ UnsupportedOperationException
    }
}

批量操作

java
public class BatchOperations {

    public static void main(String[] args) {
        // 填充
        List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
        Collections.fill(list, "x");
        System.out.println("fill: " + list);  // [x, x, x]

        // 复制(目标列表要足够大)
        List<String> src = Arrays.asList("1", "2", "3");
        List<String> dest = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
        Collections.copy(dest, src);
        System.out.println("copy: " + dest);  // [1, 2, 3, d]

        // 交换
        List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        Collections.swap(nums, 0, 3);  // 交换索引 0 和 3
        System.out.println("swap: " + nums);  // [4, 2, 3, 1]

        // 旋转(所有元素向右移动指定位置)
        List<String> rotate = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
        Collections.rotate(rotate, 2);  // 向右旋转 2 位
        System.out.println("rotate: " + rotate);  // [d, e, a, b, c]
    }
}

Arrays:数组处理利器

基本操作

java
public class ArraysDemo {

    public static void main(String[] args) {
        int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};

        // 排序
        Arrays.sort(arr);
        System.out.println("排序: " + Arrays.toString(arr));

        // 部分排序
        int[] partial = {5, 4, 3, 2, 1};
        Arrays.sort(partial, 0, 3);  // 只排序前 3 个
        System.out.println("部分排序: " + Arrays.toString(partial));  // [3, 4, 5, 2, 1]

        // 二分查找
        System.out.println("binarySearch: " + Arrays.binarySearch(arr, 5));

        // 填充
        int[] filled = new int[5];
        Arrays.fill(filled, 100);
        System.out.println("fill: " + Arrays.toString(filled));  // [100, 100, 100, 100, 100]

        // 比较
        int[] a1 = {1, 2, 3};
        int[] a2 = {1, 2, 3};
        System.out.println("equals: " + Arrays.equals(a1, a2));  // true
    }
}

数组转 List

java
public class ArraysAsList {

    public static void main(String[] args) {
        String[] array = {"a", "b", "c"};

        // ✅ Arrays.asList:返回固定大小的 List
        List<String> list = Arrays.asList(array);
        System.out.println("asList: " + list);  // [a, b, c]

        // ⚠️ 注意:返回的 List 不能 add/remove(底层是数组)
        // list.add("d");  // ❌ UnsupportedOperationException

        // ✅ 如果需要可变 List
        List<String> mutable = new ArrayList<>(Arrays.asList(array));
        mutable.add("d");  // ✅ OK

        // ✅ JDK 9+:List.of 也行
        List<String> jdk9List = List.of("a", "b", "c");
        // jdk9List.add("d");  // ❌ 也不行
    }
}

并行排序(JDK 8+)

java
public class ParallelSort {

    public static void main(String[] args) {
        // 大数组用并行排序,利用多核 CPU
        int[] large = new int[10_000_000];
        Random rand = new Random();
        for (int i = 0; i < large.length; i++) {
            large[i] = rand.nextInt();
        }

        long start = System.nanoTime();
        Arrays.parallelSort(large);  // JDK 8+ 并行排序
        long end = System.nanoTime();

        System.out.println("并行排序耗时: " + (end - start) / 1_000_000 + "ms");
        // 对于大数组,并行排序比普通排序快很多
    }
}

Objects:null 安全的守护者

equals 和 hashCode

java
public class ObjectsEqualsHash {

    public static void main(String[] args) {
        // ✅ null 安全的 equals
        String s1 = null;
        String s2 = "hello";
        System.out.println(Objects.equals(s1, s2));  // false
        System.out.println(Objects.equals(null, null));  // true

        // ❌ 普通 equals 会 NPE
        // s1.equals(s2);  // NPE

        // 深比较(数组)
        int[] arr1 = {1, 2, 3};
        int[] arr2 = {1, 2, 3};
        System.out.println(Objects.equals(arr1, arr2));  // false(比较引用)
        System.out.println(Arrays.equals(arr1, arr2));    // true(比较内容)

        // hashCode(处理 null)
        System.out.println(Objects.hash("a", 1, null));  // 自动处理 null
    }
}

toString 和 requireNonNull

java
public class ObjectsUtils {

    public static void main(String[] args) {
        // ✅ null 安全的 toString
        String nullStr = null;
        System.out.println(Objects.toString(nullStr));           // "null"
        System.out.println(Objects.toString(nullStr, "默认值")); // "默认值"

        // ✅ requireNonNull:参数校验
        String name = null;
        try {
            String result = Objects.requireNonNull(name, "name 不能为空");
        } catch (NullPointerException e) {
            System.out.println("捕获: " + e.getMessage());  // name 不能为空
        }

        // ✅ 判断方法
        System.out.println(Objects.isNull(null));     // true
        System.out.println(Objects.nonNull("str"));    // true

        // ✅ compare(JDK 7+)
        System.out.println(Objects.compare("abc", "abd", String::compareTo));  // -1
    }
}

StringUtils:字符串处理(Apache Commons)

判断方法

java
public class StringUtilsJudge {

    public static void main(String[] args) {
        // isEmpty vs isBlank
        System.out.println(StringUtils.isEmpty(""));      // true
        System.out.println(StringUtils.isEmpty(null));   // true
        System.out.println(StringUtils.isBlank("   "));  // true(空白字符)
        System.out.println(StringUtils.isBlank(null));    // true

        // 判断数字/字母/空白
        System.out.println(StringUtils.isNumeric("123"));     // true
        System.out.println(StringUtils.isNumericSpace("12 3")); // true
        System.out.println(StringUtils.isAlpha("abc"));        // true
        System.out.println(StringUtils.isAlphaSpace("a b"));   // true
    }
}

操作方法

java
public class StringUtilsOps {

    public static void main(String[] args) {
        String str = "  hello world  ";

        // 去空白
        System.out.println("trim: '" + StringUtils.trim(str) + "'");    // 'hello world'
        System.out.println("strip: '" + StringUtils.strip(str) + "'"); // 'hello world'

        // 大小写
        System.out.println(StringUtils.upperCase("abc"));   // ABC
        System.out.println(StringUtils.lowerCase("ABC"));   // abc
        System.out.println(StringUtils.capitalize("abc"));  // Abc

        // 截取
        System.out.println(StringUtils.left("abcde", 3));    // abc
        System.out.println(StringUtils.right("abcde", 3));   // cde
        System.out.println(StringUtils.mid("abcde", 1, 2));  // bc

        // 重复和填充
        System.out.println(StringUtils.repeat("ab", 3));       // ababab
        System.out.println(StringUtils.leftPad("abc", 6, '0')); // 000abc
        System.out.println(StringUtils.rightPad("abc", 6, '0')); // abc000

        // 反转
        System.out.println(StringUtils.reverse("abcd"));  // dcba
    }
}

CollectionUtils:集合操作(Apache Commons)

java
public class CollectionUtilsDemo {

    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("a", "b", "c");
        List<String> list2 = Arrays.asList("b", "c", "d");

        // 集合运算
        System.out.println("交集: " + CollectionUtils.intersection(list1, list2));  // [b, c]
        System.out.println("并集: " + CollectionUtils.union(list1, list2));         // [a, b, c, d]
        System.out.println("差集: " + CollectionUtils.subtract(list1, list2));       // [a]

        // 判断
        System.out.println(CollectionUtils.isEmpty(null));     // true
        System.out.println(CollectionUtils.isEmpty(list1));    // false
        System.out.println(CollectionUtils.isNotEmpty(list1)); // true

        // 判断包含
        System.out.println(CollectionUtils.containsAny(list1, "a", "x"));   // true
        System.out.println(CollectionUtils.containsAll(list1, "a", "b"));   // true
    }
}

Stream 工具(JDK 8+)

java
public class StreamUtils {

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // 过滤和收集
        List<Integer> evens = nums.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        System.out.println("偶数: " + evens);  // [2, 4, 6, 8, 10]

        // 映射
        List<Integer> squares = nums.stream()
            .map(n -> n * n)
            .collect(Collectors.toList());
        System.out.println("平方: " + squares);

        // 聚合
        int sum = nums.stream().mapToInt(Integer::intValue).sum();
        System.out.println("求和: " + sum);

        // 分组
        Map<String, List<Integer>> grouped = nums.stream()
            .collect(Collectors.groupingBy(n -> n % 2 == 0 ? "偶" : "奇"));
        System.out.println("分组: " + grouped);

        // 字符串连接
        String joined = nums.stream()
            .map(String::valueOf)
            .collect(Collectors.joining(", "));
        System.out.println("连接: " + joined);
    }
}

工具类速查表

场景工具类推荐方法
集合排序Collectionssort(), reverseOrder()
集合查找CollectionsbinarySearch()(需先排序)
集合极值Collectionsmax(), min()
数组排序Arrayssort(), parallelSort()
数组比较Arraysequals(), deepEquals()
null 安全Objectsequals(), requireNonNull()
字符串判断StringUtilsisEmpty(), isBlank()
字符串操作StringUtilstrim(), capitalize()
集合运算CollectionUtilsintersection(), union()
Stream 聚合Stream APIcollect(), groupingBy()

要点回顾

  • Collections:排序、二分查找、最大最小值、不可变集合
  • Arrays:排序、比较、asList 注意不可变特性
  • Objects:null 安全的 equals/toString/requireNonNull
  • Apache Commons:StringUtils、CollectionUtils 提供增强功能
  • Stream API:JDK 8+ 的函数式集合操作

工具类是前人经验的结晶,善用它们让你的代码更简洁、更安全。

基于 VitePress 构建