首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 集合求和、最大值、最小值通用工具類實現

     編輯:Java 相關知識

設計目標

提供一組泛型、空安全、支援可變參數與 Collection的數學工具方法,避免業務代碼中重複編寫迴圈邏輯,並統一異常處理風格。

完整實現代碼

package com.happyelements.athene.game.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Collection;

public final class MathUtil {
    private MathUtil() {} // 工具類禁止實例化

    // ==================== 最小值 ====================
    public static <T extends Comparable<T>> T min(T... values) {
        return min(Lists.newArrayList(values));
    }

    public static <T extends Comparable<T>> T min(Collection<T> values) {
        Preconditions.checkNotNull(values, "集合不能為 null");
        T min = null;
        for (T t : values) {
            Preconditions.checkNotNull(t, "集合元素不能包含 null");
            if (min == null || t.compareTo(min) < 0) {
                min = t;
            }
        }
        return min; // 空集合返回 null
    }

    // ==================== 最大值 ====================
    public static <T extends Comparable<T>> T max(T... values) {
        return max(Lists.newArrayList(values));
    }

    public static <T extends Comparable<T>> T max(Collection<T> values) {
        Preconditions.checkNotNull(values, "集合不能為 null");
        T max = null;
        for (T t : values) {
            Preconditions.checkNotNull(t, "集合元素不能包含 null");
            if (max == null || t.compareTo(max) > 0) {
                max = t;
            }
        }
        return max;
    }

    // ==================== 求和 ====================
    public static Integer sum(Collection<Integer> values) {
        Preconditions.checkNotNull(values, "集合不能為 null");
        int sum = 0;
        for (Integer v : values) {
            Preconditions.checkNotNull(v, "集合元素不能包含 null");
            sum += v;
        }
        return sum;
    }

    public static Integer sum(Integer... values) {
        return sum(Lists.newArrayList(values));
    }
}

關鍵設計決策解析

決策點選擇理由
參數形式可變參數 + Collection 重載兼顧 min(1,2,3) 便利性與 min(list) 通用性
空集合行為返回 null避免拋出異常打斷流程,調用方自行判斷
null 元素處理Preconditions.checkNotNull 拋 NPE快速失效,暴露數據質量問題
泛型約束<T extends Comparable<T>>確保元素可比較,支援所有標準類型及自定義實現 Comparable 的類
依賴庫Guava (Preconditions, Lists)項目已引入,碼簡潔可靠;若無 Guava 可換為 JDK 原生判斷

使用示例

// 可變參數調用
Integer minVal = MathUtil.min(5, 2, 9, 1);        // 1
Integer maxVal = MathUtil.max(5, 2, 9, 1);        // 9
Integer sumVal = MathUtil.sum(5, 2, 9, 1);        // 17

// Collection 調用
List<Double> prices = Arrays.asList(19.9, 29.9, 9.9);
Double minPrice = MathUtil.min(prices);           // 9.9
Double maxPrice = MathUtil.max(prices);           // 29.9

// 自定義類型(需實現 Comparable)
List<User> users = ...;
User oldest = MathUtil.max(users); // 依賴 User.compareTo 實現

擴展建議

  • 新增 average()、median()、percentile() 等統計函數
  • 引入 Comparator 參數版本,支援非自然順序比較
  • 對於大數據量場景,提供 Stream 版本利用並行流加速
  • 整合 Optional 返回類型(Java 8+),更明確表達「可能為空」語義

總結

這個 MathUtil 類展示了工具類設計的最佳實踐:泛型復用、防禦性編程、API 對稱性、零依賴業務邏輯。將此類基礎設施沉澱到公共庫,能顯著降低業務代碼的圈複雜度與 Bug 率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved