package com.mh.common.utils; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import java.util.function.BiPredicate; /** * @author LJF * @version 1.0 * @project EEMCS * @description 数据比较值 * @date 2025-02-21 15:56:56 */ public class BigDecimalUtils { // 定义运算符与比较逻辑的映射 private static final Map> OPERATORS = new HashMap<>(); static { // 初始化支持的运算符 OPERATORS.put(">", (a, b) -> a.compareTo(b) > 0); OPERATORS.put(">=", (a, b) -> a.compareTo(b) >= 0); OPERATORS.put("<", (a, b) -> a.compareTo(b) < 0); OPERATORS.put("<=", (a, b) -> a.compareTo(b) <= 0); OPERATORS.put("==", (a, b) -> a.compareTo(b) == 0); OPERATORS.put("=", (a, b) -> a.compareTo(b) == 0); // 添加对 = 运算符的支持 OPERATORS.put("!=", (a, b) -> a.compareTo(b) != 0); } /** * 根据运算符比较两个 BigDecimal * @param operator 运算符(如 ">", ">=") * @param a 第一个数值 * @param b 第二个数值 * @return 比较结果 * @throws IllegalArgumentException 如果运算符无效 */ public static boolean compare(String operator, BigDecimal a, BigDecimal b) { BiPredicate predicate = OPERATORS.get(operator); if (predicate == null) { throw new IllegalArgumentException("不支持的运算符: " + operator); } return predicate.test(a, b); } public static void main(String[] args) { BigDecimal a = new BigDecimal("10.00"); BigDecimal b = new BigDecimal("10.00"); System.out.println(compare(">", a, b)); System.out.println(compare(">=", a, b)); System.out.println(compare("<", a, b)); System.out.println(compare("<=", a, b)); System.out.println(compare("==", a, b)); System.out.println(compare("!=", a, b)); } }