Java教程

Java数学运算工具类

本文主要是介绍Java数学运算工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.clinicalresearch.core.utils;

import com.clinicalresearch.core.dto.NearDto;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MathUtils {


    /**
     * 获取最大百分比
     *
     * @param value
     * @return
     */
    public static String maxNumPercent(String[] value) {
        Set<String> set = new LinkedHashSet<>(Arrays.asList(value));
        Map<String, Integer> countMap = new LinkedHashMap<>();
        for (String var : set) {
            int count = 0;
            for (String v : value) {
                if (var.equals(v)) {
                    count++;
                }
            }
            countMap.put(var, count);
        }
        //求和
        int sum = 0;
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            sum += entry.getValue();
        }
        //求最大值
        int max = 0;
        String maxKey = "";
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            String key = entry.getKey();
            Integer entryValue = entry.getValue();
            if (StringUtils.isNotBlank(key)) {
                if (entryValue > max) {
                    max = entryValue;
                    maxKey = key;
                }
            }
        }
        String numPercent = "";
        if (sum != 0) {
            Double value1 = Double.valueOf(max) / Double.valueOf(sum);
            numPercent = getNumPercent(value1);
        }

        return maxKey + "(" + numPercent + ")";
    }


    /**
     * 数据的标准差
     *
     * @param value
     * @return
     */
    public static double sd(String[] value) {
        double mean = mean(value);//平均值
        double sum = 0.0;
        for (String num : value) {
            if (StringUtils.isNotBlank(num) && !isContainSpecalSymbol(num)) {
                double v = Double.valueOf(num) - mean;
                sum += Math.pow(v, 2);
            }
        }
        double sqrt = Math.sqrt(sum / value.length);
        return sqrt;
    }

    /**
     * 平均值
     *
     * @param value
     * @return
     */
    public static double mean(String[] value) {
        double sum = 0.0;
        for (String num : value) {
            if (StringUtils.isNotBlank(num) && !isContainSpecalSymbol(num))
                sum += Double.valueOf(num);
        }
        return Double.valueOf(getRoundingModeNum(sum / value.length));
    }

    /**
     * 中位数
     *
     * @param value
     * @return
     */
    public static double median(String[] value) {
        List<String> list = getNotEmptyValue(value);
        int length = list.size();
        double median;
        if (length % 2 == 0) {
            int first = (length / 2) - 1;
            int next = first + 1;
            median = (Double.valueOf(list.get(first)) + Double.valueOf(list.get(next))) / 2;
        } else {
            int index = ((length + 1) / 2) - 1;
            median = Double.valueOf(list.get(index));
        }

        return Double.valueOf(getRoundingModeNum(median));
    }

    /**
     * 临近均值
     *
     * @param flyPast
     * @param value
     * @return
     */
    public static NearDto nearMean(Integer flyPast, String[] value) {
        NearDto nearDto = new NearDto();
        List<String> valueList = Arrays.asList(value);
        Map<Integer, String> lostData = getLostValueIndex(valueList);
        for (Integer key : lostData.keySet()) {
            List<String> subList = new ArrayList<>();
            List<String> leftList = valueList.subList((key - flyPast < 0 ? 0 : key - flyPast), key);
            subList.addAll(leftList);
            List<String> rightList = valueList.subList(key + 1, (key + flyPast + 1 > valueList.size() ? valueList.size() : key + flyPast + 1));
            subList.addAll(rightList);
            double sum = 0.0;
            for (String var : subList) {
                if (!isContainSpecalSymbol(var)) {
                    sum += Double.valueOf(var);
                }
            }
            Double avg = sum / flyPast / 2;
            value[key] = String.valueOf(getRoundingModeNum(avg));
        }
        Multimap<String, String> multiMap = LinkedListMultimap.create();
        for (Integer index : lostData.keySet()) {
            multiMap.put(lostData.get(index), value[index]);
        }
        nearDto.setMultiMap(multiMap);
        nearDto.setNearValue(value);
        return nearDto;
    }

    /**
     * 临近中位数
     *
     * @param flyPast
     * @param value
     * @return
     */
    public static NearDto nearmedian(Integer flyPast, String[] value) {
        NearDto nearDto = new NearDto();
        List<String> valueList = Arrays.asList(value);
        Map<Integer, String> lostData = getLostValueIndex(valueList);
        for (Integer key : lostData.keySet()) {
            List<String> subList = new ArrayList<>();
            List<String> leftList = valueList.subList((key - flyPast < 0 ? 0 : key - flyPast), key);
            subList.addAll(leftList);
            List<String> rightList = valueList.subList(key + 1, (key + flyPast + 1 > valueList.size() ? valueList.size() : key + flyPast + 1));
            subList.addAll(rightList);
            String[] strings = subList.toArray(new String[subList.size()]);
            double median = median(strings);
            value[key] = String.valueOf(median);
        }
        Multimap<String, String> multiMap = LinkedListMultimap.create();
        for (Integer index : lostData.keySet()) {
            multiMap.put(lostData.get(index), value[index]);
        }
        nearDto.setMultiMap(multiMap);
        nearDto.setNearValue(value);
        return nearDto;
    }


    /**
     * 获取缺失值,以及缺失值对应的索引
     *
     * @param valueList
     * @return
     */
    public static Map<Integer, String> getLostValueIndex(List<String> valueList) {
        Map<Integer, String> lostData = new LinkedHashMap<>();
        int index = 0;
        for (String var : valueList) {
            if (StringUtils.isBlank(var)) {
                lostData.put(index, var);
            } else {
                if (isContainSpecalSymbol(var)) {
                    lostData.put(index, var);
                }
            }
            index++;
        }
        return lostData;
    }

    /**
     * 获取不为空的排序后的数据
     *
     * @param value
     * @return
     */
    private static List<String> getNotEmptyValue(String[] value) {
        List<String> list = new ArrayList<>();
        for (String var : value) {
            if (StringUtils.isNotBlank(var) && !isContainSpecalSymbol(var)) {
                list.add(var);
            }
        }
        Collections.sort(list);
        return list;
    }


    /**
     * 获取最小跨度数
     *
     * @param value
     * @return
     */
    public static Integer getMinFlyPast(String[] value) {
        int index = 0;
        //获取首个特殊字符或者null的位置
        for (int i = 0; i < value.length; i++) {
            if (isContainSpecalSymbol(value[i])) {
                index = i;
                break;
            }
        }
        //如果首个位置是null或者特殊字符
        if (index == 0) {
            for (int i = 0; i < value.length; i++) {
                if (StringUtils.isNotBlank(value[i])) {
                    if (isNumeric(value[i])) {
                        break;
                    }
                }
                index++;
            }
            return index + 1;
        }
        int left = 0, right = 0;
        for (int i = index; i >= 0; i--) {
            if (isContainSpecalSymbol(value[i])) {
                break;
            } else {
                left++;
            }
        }
        for (int i = index; i < value.length; i++) {
            if (isContainSpecalSymbol(value[i])) {
                break;
            } else {
                right++;
            }
        }
        return right > left ? right : left;

    }

    /**
     * 是否包含特殊字符
     *
     * @param var
     * @return
     */
    public static boolean isContainSpecalSymbol(String var) {
        boolean find = false;
        if (StringUtils.isNotBlank(var)) {
            String regEx = "[+\\-*~`!@#$%^&()=_ {}|<>?/:;\\\\'\\[\\][a-zA-Z]]";
            String regEx2 = "[\\u4e00-\\u9fa5]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(StringUtils.trim(var));
            Pattern p2 = Pattern.compile(regEx2);
            Matcher m2 = p2.matcher(var);
            if (m.find() || m2.find()) {
                find = true;
            }
        } else {
            find = true;
        }


        return find;
    }

    /**
     * 获取缺失值
     *
     * @param value
     * @return
     */
    public static Map<String, String> getMissingValue(String[] value) {
        int nullValue = 0;
        Map<String, String> resultMap = new LinkedHashMap<>();
        String regEx = "[+\\-*~`!@#$%^&()=_ {}|<>?/:;\\\\'\\[\\]]";
        Pattern p = Pattern.compile(regEx);
        List<String> symbolList = new ArrayList<>();
        for (String var : value) {
            if (StringUtils.isBlank(var)) {
                nullValue++;
            }
            Matcher m = p.matcher(StringUtils.trim(var));
            if (m.find()) {
                String group = m.group();
                symbolList.add(group);
            }
        }
        resultMap.put(null, nullValue + "");
        for (String symbol : symbolList) {
            int count = 0;
            for (String var : value) {
                if (symbol.equals(var)) {
                    count++;
                }
            }
            resultMap.put(symbol, count + "");
        }

        return resultMap;
    }

    /**
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        String regEx = "^\\d*$|^\\d*[.]\\d*$|^-\\d*$|^-\\d*[.]\\d*$";
        Pattern p = Pattern.compile(regEx);
        Matcher matcher = p.matcher(str);
        return matcher.matches();

    }

    public static String getNumber(String value) {
        if (isNumeric(value)) {
            Double dValue = Double.valueOf(value);
            int intValue = dValue.intValue();
            if (intValue == dValue) {
                return intValue + "";
            }
        }
        return value;
    }


    /**
     * 计算器
     *
     * @param optSymbol 操作符号
     * @param num1      数1
     * @param num2      数2
     * @return
     */
    public static String calculator(String optSymbol, String num1, String num2) {
        if (!optSymbol.equals("~")) {
            if (StringUtils.isBlank(num1) || StringUtils.isBlank(num2)) {
                return null;
            }
        }
        boolean numeric = StringUtils.isBlank(num1) ? false : isNumeric(num1);
        boolean numeric1 = StringUtils.isBlank(num2) ? false : isNumeric(num2);
        if (optSymbol.equals("~")) {
            if (!numeric && !numeric1) {
                return null;
            }
        } else {
            if (!numeric || !numeric1) {
                return null;
            }
        }

        String result = null;
        switch (optSymbol) {
            case "+":
                result = getBigDecimal(num1).add(getBigDecimal(num2)).toString();
                break;
            case "-":
                result = getBigDecimal(num1).subtract(getBigDecimal(num2)).toString();
                break;
            case "*":
                result = getBigDecimal(num1).multiply(getBigDecimal(num2)).toString();
                break;
            case "/":
                BigDecimal bigDecimal = getBigDecimal(num2);
                if (bigDecimal.doubleValue() != 0) {
                    result = getBigDecimal(num1).divide(bigDecimal, BigDecimal.ROUND_HALF_UP).toString();
                }

                break;
            case ">":
                int i = getBigDecimal(num1).compareTo(getBigDecimal(num2));
                if (i > 0) {
                    result = "1";
                } else if (i < 0) {
                    result = "0";
                }
                break;
            case "<":
                Double v1 = Double.valueOf(num1);
                Double v2 = Double.valueOf(num2);
                if (v1 > v2) {
                    result = "0";
                } else if (v1 < v2) {
                    result = "1";
                }
                break;
            case "≥":
                Double v3 = Double.valueOf(num1);
                Double v4 = Double.valueOf(num2);
                if (v3 >= v4) {
                    result = "1";
                } else {
                    result = "0";
                }

                break;
            case "≤":
                Double v5 = Double.valueOf(num1);
                Double v6 = Double.valueOf(num2);
                if (v5 > v6) {
                    result = "0";
                } else {
                    result = "1";
                }
                break;
            case "=":
                Double v7 = Double.valueOf(num1);
                Double v8 = Double.valueOf(num2);
                if (v7.equals(v8)) {
                    result = "1";
                } else {
                    result = "0";
                }
                break;
            case "≠":
                Double v9 = Double.valueOf(num1);
                Double v10 = Double.valueOf(num2);
                if (!v9.equals(v10)) {
                    result = "1";
                } else {
                    result = "0";
                }
                break;
            case "^":
                int intValue = getBigDecimal(num2).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                result = getBigDecimal(num1).pow(intValue).toString();
                break;
            case "~":
                if (StringUtils.isNotBlank(num1)) {
                    int i1 = ~getBigDecimal(num1).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                    result = i1 + "";
                } else if (StringUtils.isNotBlank(num2)) {
                    int i1 = ~getBigDecimal(num2).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                    result = i1 + "";
                }
                break;
            case "&":
                int intValue1 = getBigDecimal(num1).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                int intValue2 = getBigDecimal(num2).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                if (intValue1 > 0 && intValue2 > 0) {
                    result = "1";
                } else {
                    result = "0";
                }
                break;
            case "|":
                int intValue3 = getBigDecimal(num1).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                int intValue4 = getBigDecimal(num2).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                if (intValue3 < 1 && intValue4 < 1) {
                    result = "0";
                } else {
                    result = "1";
                }
                break;
        }

        return result;

    }

    private static BigDecimal getBigDecimal(String number) {
        return new BigDecimal(number);
    }

    /**
     * 获取数据的百分比格式
     *
     * @param value
     * @return
     */
    public static String getNumPercent(Double value) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        String format = nf.format(value);
        return format;
    }

    //获取四舍五入后的数字
    public static String getRoundingModeNum(Double value) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setRoundingMode(RoundingMode.HALF_UP);
        nf.setMaximumFractionDigits(0);
        return nf.format(value);
    }

    public static String getRoundingModeNum(Double value, int num) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setRoundingMode(RoundingMode.HALF_UP);
        nf.setMaximumFractionDigits(num);
        return nf.format(value);
    }

    /**
     * 格式化时间
     * @param date
     * @return
     */
    public static String getFormatDateValue(String date) {
        try {
            if(StringUtils.isBlank(date)){
                return null;
            }
            String pattern="yyyy-MM-dd HH:mm:ss";
            String regEx = "\\d{4}\\-\\d{2}\\-\\d{4}:\\d{2}:\\d{2}";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(date);
            if(m.find()){
                pattern="yyyy-MM-ddHH:mm:ss";
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            Date parse = simpleDateFormat.parse(date);
            return  getFormatDateValue(parse);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 格式化时间
     * @param date
     * @return
     */
    public static String getFormatDateValue(Date date) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            return simpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date getFormatDate(String date) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            return simpleDateFormat.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

这篇关于Java数学运算工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!