java项目中常用的工具类

package util;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumberUtil {
/**
* 1 为了防止浮点数以科学计数法显示出来,通过NumberFormat转化成普通计数法,这里指定最多精确到小数点后4位

* @param value
*            浮点型数据
* @param length
*            精确到小数点后的位数
*/
public static String convertDoubleToString(double value, int length) {
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();// 返回当前默认语言环境的通用数值格式。
df.setMinimumFractionDigits(length); // 返回数的小数部分所允许的最小位数。
df.setMaximumFractionDigits(length); // 返回数的小数部分所允许的最大位数。
return df.format(value);
}


/**
* 3 将字符串转化成double类型

* @param value
*            字符串
*/
public static double convertStringToDouble(String value) {
if (value.equals("") || value == null) {
value = "0.0";
}
value = replaceString(value, ",", "");// 将value中的","替换成""
return Double.valueOf(value);
}


/**
* 2 将指定的字符串替换成新的字符串:将str中出现的字符串oldStr替换为newStr

* @param str
* @param oldStr
*            子字符串
* @param newStr
*            新子字符串
* @return
*/
private static String replaceString(String str, String oldStr, String newStr) {
int pos = 0;
if (str == null) {
return null;
}
String tmp = str;
String resultStr = "";
// 字符串.indexOf(子字符串):返回指定子字符串在此字符串中第一次出现处的索引。
// 将str中出现的oldStr替换为newStr
while ((pos = tmp.indexOf(oldStr)) >= 0) {
resultStr = resultStr + tmp.substring(0, pos) + newStr;
tmp = tmp.substring(pos + oldStr.length(), tmp.length());
}
if (tmp.equals("")) {
return resultStr;
}
return resultStr + tmp;
}


/**
* 4 判断字符串是否为零

* @param strNum
* @return
*/
public static boolean equalZero(String strNum) {
boolean ref = false;
if (!strNum.equals("") || strNum != null) {
ref = Double.parseDouble(strNum) == 0 ? true : false;
}
return ref;
}


/**
* 5 将一个字符串转化成一个固定长度的字符串,位数不够在前面补0

* @param str
* @param length
*            指定字符串固定的长度
* @return
*/
public static String fillStr(String str, int length) {
int len = str.length();
int replaceLen = length - len;
String newStr = str;
if (len < length) {
for (int i = 0; i < replaceLen; i++) {
newStr = "0".concat(newStr);// 将指定字符串newStr连接到此字符串"0"的结尾。
}
return newStr;
} else {
return str;
}
}


/**
* 6 将前面用0补齐的字符串转化成正常的字符串

* @param String
* @return String
*/
public static String convertStringToIntString(String value) {
return String.valueOf(Integer.valueOf(value));// Integer.valueOf(value)将前面带0的数值字符串转换成不带0的数值字符串
}


/**
* 7 以传入参数numinitial的形式格式化一个字符串,按照0.0000格式传递

* @param str
* @param numinitial
* @return
*/
public static String formatStr(String str, String numinitial) {
str = isValide(str) ? str : "0"; // 判断字符串是否有效
int scale = (numinitial.length() - 2 > 0 ? numinitial.length() - 2 : 0);
BigDecimal bd = new BigDecimal(str);
String result = bd.setScale(scale, BigDecimal.ROUND_HALF_DOWN)
.toString();
return result;
}


/**
* 判断字符串是否有效

* @param str
* @return
*/
public static boolean isValide(String str) {
if (str.equals("") || str == null) {
return false;
}
return true;
}


/**
* 8 清除掉数值中小数部分多余的0 2.3300---->2.33

* @param args
*/
public static String cleanZero(String num) {
if (num.indexOf("0") > 0) { // 该数是一个小数
byte[] c = num.getBytes();// l将字符串转化成字符数组
int i = c.length - 1;


for (; ((char) c[i]) == '0'; i--)
;
if (c[i] == '.') {
return new String(c, 0, i);
} else {
return new String(c, 0, i + 1);
}
} else {
return num;
}


}


public static void main(String[] args) {
// 1
System.out.println(convertDoubleToString(99.99, 9));
// 2
System.out.println(replaceString("ren,peng,liang", ",", ";"));
// 3
System.out.println(convertStringToDouble("20.,66"));
// 4
System.out.println(equalZero("0"));
// 5
System.out.println(fillStr("5555", 8));
// 6
System.out.println(convertStringToIntString("00005555"));
// 7
/*
* 如果格式为:0.00000;如果小数点后的位数超过5位,从第六位开始进行四舍五入 66.666664---->66.66666
* 66.666665----->66.66667
*/
System.out.println(formatStr("66.666664", "0.00000"));
// 8
System.out.println(cleanZero("22.3300"));


}

}



package com.ielpm.paygate.utils;


import javax.servlet.http.HttpServletRequest;


import com.google.common.base.Strings;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


/**
 * Created by zhangzw on 2015/12/1.
 */
public class RequestUtils {


    /**
     * 获取request参数,封装到map中,并按key值排序
     * @param request
     * @return
     */
    public static TreeMap getParameterMap(HttpServletRequest request){
        TreeMap map = new TreeMap();
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
            String param = en.nextElement();
            String value = request.getParameter(param.toString());
            map.put(param, value);
        }
        return map;
    }


    /**
     * 解析queryString
     * @param queryString 请求参数字符串
     * @param enc      编码
     * @return
     */
    public static Map getParamsMap(String queryString, String enc) {
        Map paramsMap = new TreeMap();
        if (queryString != null && queryString.length() > 0) {
            int ampersandIndex, lastAmpersandIndex = 0, tmpIndex = 0;
            String subStr, param, value;
            do {
                ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
                if (ampersandIndex > 0) {
                    subStr = queryString.substring(lastAmpersandIndex, ampersandIndex - 1);
                    lastAmpersandIndex = ampersandIndex;
                } else {
                    subStr = queryString.substring(lastAmpersandIndex);
                }
                
                tmpIndex = subStr.indexOf('=');
                param = subStr.substring(0,tmpIndex);
                value = subStr.substring(tmpIndex+1);
                try {
                    value = URLDecoder.decode(value, enc);
                } catch (UnsupportedEncodingException ignored) {
                }
//                if (paramsMap.containsKey(param)) {
//                    values = (String[])paramsMap.get(param);
//                    int len = values.length;
//                    newValues = new String[len + 1];
//                    System.arraycopy(values, 0, newValues, 0, len);
//                    newValues[len] = value;
//                } else {
//                    newValues = new String[] { value };
//                }
                if(!"".equals(param))
                    paramsMap.put(param, value);
            } while (ampersandIndex > 0);
        }
        return paramsMap;
    }


    
    public static Map getRequestMap(HttpServletRequest request){
    Map paramsMap = new TreeMap();
    paramsMap = getParameterMap(request);
    String queryString = request.getQueryString();
    if(!Strings.isNullOrEmpty(queryString)){
    paramsMap.putAll(getParamsMap(queryString, "utf-8"));
    }
    return paramsMap;
    }
    
    
    /**
* 获取当前使用者ip

* @return
*/
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (null != ip && !"".equals(ip)) {
String[] ips = ip.split(",");
for (String s : ips) {
if (!"unknown".equals(s)) {
ip = s;
break;
}
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip == null ? "" : ip;
}




}



package util;


import java.util.Comparator;
/**
 * 
 * 字符串之间大小的比较
 * @author Administrator
 *
 */
public class ComparatorUtil implements Comparator {


@Override
public int compare(String o1, String o2) {
int len1 = o1.length();
int len2 = o2.length();
int lim = Math.min(len1, len2);
char v1[] = o1.toCharArray();
char v2[] = o2.toCharArray();


int k = 0;
if (len1 > len2) {
return len1 - len2;
}
if (len1 < len2) {
return len1 - len2;
}
//判断两个等长度的字符串
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
            k++;
}
return 0;
}


}

package util;


import java.math.BigDecimal;


public class MathUtil {
/**
* 1 计算两个数字字符串相加

* @param strFirst
* @param StrSecond
* @return
*/
public static String addTwoNumStr(String strFirst, String StrSecond) {
if (strFirst.equalsIgnoreCase("")) {
strFirst = "0";
}
if (StrSecond.equalsIgnoreCase("")) {
strFirst = "0";
}
// 通过BigDecimal将字符串转化成类型数值
BigDecimal obj = new BigDecimal(strFirst);
BigDecimal obj1 = new BigDecimal(StrSecond);
return (obj.add(obj1).toString());
}


/**
* 2 计算两个数字字符串相加,以传入参数的形式返回结果字符串

* @param strFirst
* @param StrSecond
* @param numinitial
* @return
*/
public static String addTwoNumStr(String strFirst, String StrSecond,
String numinitial) {
if (strFirst.equalsIgnoreCase("")) {
strFirst = "0";
}
if (StrSecond.equalsIgnoreCase("")) {
strFirst = "0";
}
// 通过BigDecimal将字符串转化成类型数值
BigDecimal obj = new BigDecimal(strFirst);
BigDecimal obj1 = new BigDecimal(StrSecond);
String result = obj.add(obj1).toString();
return (NumberUtil.formatStr(result, numinitial));
}


/**
* 3 得到某个数的相反数

* @param numStr
* @return
*/
public static String strSign(String numStr) {
if (!NumberUtil.isValide(numStr)) {
numStr = "0";
}
BigDecimal obj1 = new BigDecimal(numStr);
return (obj1.negate().toString());
}


/**
* 4
*  得到某个数的绝对值(得到某个BigDecimal实例的绝对值)

* @param numStr
* @return
*/
public static String strAbs(String numStr) {
if (!NumberUtil.isValide(numStr)) {
numStr = "0";
}
BigDecimal obj1 = new BigDecimal(numStr);
return (obj1.abs().toString());
}
/**
* 9
* 两个数值字符串相乘,返回结果字符串

* @param numStr
* @return
*/
public static String multTwoNumStr(String numStr1,String numStr2) {
BigDecimal obj1 = new BigDecimal(numStr1);
BigDecimal obj2 = new BigDecimal(numStr2);
BigDecimal result = obj1.multiply(obj2);
return result.toString();
}


/**
* 5 判断两个数是否相等:如果相等返回0,不相等返回-1

* @param strFirst
* @param StrSecond
* @return
*/
public static int equals(String strFirst, String StrSecond) {
BigDecimal obj = new BigDecimal(strFirst);
BigDecimal obj1 = new BigDecimal(StrSecond);
return obj.compareTo(obj1);
}


/**
* 57 判断两个数是否相等:如果相等返回true,不相等返回false

* @param strFirst
* @param StrSecond
* @return
*/
public static boolean isNumberEquals(String strFirst, String StrSecond) {
BigDecimal obj = new BigDecimal(strFirst);
BigDecimal obj1 = new BigDecimal(StrSecond);
int res = obj.compareTo(obj1);
if (res == 0) {
return true;
}
if (res == -1) {
return false;
}
return false;
}


/**
* 6 数组数据求和

* @param number
* @return
*/
public static String sumNumberArrStr(String[] number) {
BigDecimal sum = new BigDecimal("0.000");
if (number != null) {
for (int i = 0; i < number.length; i++) {
sum = sum.add(new BigDecimal(number[i]));
}
}
return sum.toString();
}
/**
     * 8
     * 比较两个字符串的大小,返回结果是较小的字符串,如果比较不出来返回第一个字符串
     * @param args
     */
public static String compareTwoStrSmall(String firstStr, String secondStr) {
if (firstStr.equals("")) {
return secondStr;
}
if (secondStr.equals("")) {
return firstStr;
} else {
BigDecimal obj1 = new BigDecimal(firstStr);
BigDecimal obj2 = new BigDecimal(secondStr);
int reti = obj1.compareTo(obj2);
if (reti == -1) {
return firstStr;
} else if (reti == 0) {
return firstStr;
} else if (reti == 1) {
return secondStr;
} else {
return firstStr;
}


}


}

/**
* 10
* 两个数字字符串相除,返回结果字符串,按照scale精度要求四舍五入
* @param numStr1
* @param numStr2
* @param scale
* @return
*/
public static String divTwoNumStr(String numStr1,String numStr2,int scale) {
BigDecimal obj1 = new BigDecimal(numStr1);
BigDecimal obj2 = new BigDecimal(numStr2);
//如果除数或被除数是0,结果返回是0
if(!NumberUtil.isValide(numStr1)||!NumberUtil.isValide(numStr2)){
return "0";
}
//如果除数是0,结果返回是0
if(Double.parseDouble(numStr2)==0){
return "0";
}
BigDecimal result = obj1.divide(obj2,scale,4);
return result.toString();
}



   
public static void main(String[] args) {
// 1
System.out.println(addTwoNumStr("2", "4"));
// 2
System.out.println(addTwoNumStr("2", "44", "0.000000"));
// 3
System.out.println(strSign("20"));
// 4
System.out.println(strAbs("-20"));
// 5
System.out.println(equals("1", "1"));
// 6
System.out.println(sumNumberArrStr(new String[] { "1", "2", "3" }));
// 7
System.out.println(isNumberEquals("1", "2"));
//8
System.out.println(compareTwoStrSmall("11111","22222"));
//9
System.out.println(multTwoNumStr("11","11"));
//10
System.out.println(divTwoNumStr("20","4",2));
}
}

package util;


import java.text.DecimalFormat;


public class MoneyUtil {
/**
* 1 将数字金额转化成汉语字符串 注意:使用该方法只能精确到分:555555.55

* @param money
*            12----->壹拾贰
* @return String
*/
public static String convertMoneyToChinese(String money) {
if (money == null || money.equals("")) {
return "您转化的金额是空对象";// 空对象返回空字符串
}
/**

* 判断正负数的标志 flag=false:负数 flag=true:正数
*/
boolean flag = true;
if (money.substring(0, 1).equals("-")) {
money = money.substring(1, money.length());
flag = false;
}
String b = "壹贰叁肆伍陆柒捌玖拾";
String moneySum = money;
if (moneySum.substring(moneySum.indexOf("."), moneySum.length())
.length() < 3) {
moneySum = moneySum + "0";
}
// 将钱数补齐为15位
while (moneySum.length() < 16) {
moneySum = " " + moneySum;
}
// 将超出15位的钱数截取为15位
if (moneySum.length() > 16) {
moneySum = moneySum.substring(moneySum.length() - 16, moneySum
.length());
}
// 获取钱各位的数值
String x1 = moneySum.substring(0, 1);
String x2 = moneySum.substring(1, 2);
String x3 = moneySum.substring(2, 3);
String x4 = moneySum.substring(3, 4);
String x5 = moneySum.substring(4, 5);
String x6 = moneySum.substring(5, 6);
String x7 = moneySum.substring(6, 7);
String x8 = moneySum.substring(7, 8);
String x9 = moneySum.substring(8, 9);
String x10 = moneySum.substring(9, 10);
String x11 = moneySum.substring(10, 11);
String x12 = moneySum.substring(11, 12);
String x13 = moneySum.substring(12, 13);
// 注意把"."区分出来
String x14 = moneySum.substring(14, 15);
String x15 = moneySum.substring(15, 16);
int temp = 0;
String chinese = "";
if (!x1.equals(" ")) {
temp = Integer.parseInt(x1);
chinese = chinese + b.substring(temp - 1, temp) + "万";
}
if (!x2.equals(" ")) {
temp = Integer.parseInt(x2);
if (x2.equals("0") && !x3.equals("0")) {
chinese = chinese + "零";
}
if (!x2.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "仟";
}
}
if (!x3.equals(" ")) {
temp = Integer.parseInt(x3);
if (x3.equals("0") && !x4.equals("0")) {
chinese = chinese + "零";
}
if (!x3.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "佰";
}
}
if (!x4.equals(" ")) {
temp = Integer.parseInt(x4);
if (x4.equals("0") && !x5.equals("0")) {
chinese = chinese + "零";
}
if (!x4.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "拾";
}
}
if (!x5.equals(" ")) {
temp = Integer.parseInt(x5);
if (x5.equals("0")) {
chinese = chinese + "亿";
}
if (!x5.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "亿";
}
}
if (!x6.equals(" ")) {
temp = Integer.parseInt(x6);
if (x6.equals("0") && !x7.equals("0")) {
chinese = chinese + "零";
}
if (!x6.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "仟";
}
}
if (!x7.equals(" ")) {
temp = Integer.parseInt(x7);
if (x7.equals("0") && !x8.equals("0")) {
chinese = chinese + "零";
}
if (!x7.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "佰";
}
}
if (!x8.equals(" ")) {
temp = Integer.parseInt(x8);
if (x8.equals("0") && !x9.equals("0")) {
chinese = chinese + "零";
}
if (!x8.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "拾";
}
}
if (!x9.equals(" ")) {
temp = Integer.parseInt(x9);
if (x8.equals("0") && x10.equals("0") && x7.equals("0")
&& x6.equals("0")) {


} else if (x9.equals("0")) {
chinese = chinese + "万";
} else {
chinese = chinese + b.substring(temp - 1, temp) + "万";
}
}
if (!x10.equals(" ")) {
temp = Integer.parseInt(x10);
if (x10.equals("0") && !x11.equals("0")) {
chinese = chinese + "零";
}
if (!x10.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "仟";
}
}
if (!x11.equals(" ")) {
temp = Integer.parseInt(x11);
if (x11.equals("0") && !x12.equals("0")) {
chinese = chinese + "零";
}
if (!x11.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "佰";
}
}
if (!x12.equals(" ")) {
temp = Integer.parseInt(x12);
if (x12.equals("0") && !x13.equals("0")) {
chinese = chinese + "零";
}
if (!x12.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "拾";
}
}
if (!x13.equals(" ")) {
temp = Integer.parseInt(x13);
if (x13.equals("0") && x14.equals("0") && x12.equals(" ")
&& x15.equals("0")) {
chinese = "零元";
} else if (x13.equals("0")
&& (!x14.equals("0") || !x15.equals("0"))) {


} else if (x13.equals("0")) {
chinese = chinese + "元";
} else {
chinese = chinese + b.substring(temp - 1, temp) + "元";
}
}
if (!x14.equals(" ")) {
temp = Integer.parseInt(x14);
if (x13.equals("0") && x14.equals("0") && !x15.equals("0")) {
chinese = chinese + "零";
} else if (!x14.equals("0")) {
chinese = chinese + b.substring(temp - 1, temp) + "角";
}
}
if (!x15.equals(" ")) {
temp = Integer.parseInt(x15);
if (x15.equals("0")) {
chinese = chinese + "整";
} else {
chinese = chinese + b.substring(temp - 1, temp) + "分";
}
}
if (!flag) {
chinese = "负" + chinese;
}
return chinese;
}


/**
* 2 将","隔开的字符串形式的钱转化成浮点类型的数值的钱

* @param moneyStr
*            以","隔开的字符串形式的钱
* @return
*/
public static float changeFloat(String moneyStr) {
float floatMoney = 0;
if (null == moneyStr || " ".equals(moneyStr)) { // 如果为空相当于没有钱
return floatMoney;
}
String[] moneyStrArray = moneyStr.split(",");
String strMoney = "";
for (int i = 0; i < moneyStrArray.length; i++) {
strMoney += moneyStrArray[i];
}
floatMoney = Float.parseFloat(strMoney);
return floatMoney;
}


/**
* 3
* 将浮点型数据整数部分转化成字符串:把小数四舍五入掉
* @param args
*/
public static String formatIntegerToString(String money) {
money = NumberUtil.isValide(money) ? money : "0";
DecimalFormat f = new DecimalFormat("###,###");
return f.format(Double.parseDouble(money));
}


public static void main(String[] args) {
// 1
System.out.println(convertMoneyToChinese("12.1"));
// 2
System.out.println(changeFloat("11,12.1"));
//3
System.out.println(formatIntegerToString("20.55"));

}}

                                            集合         


集合中元素去重
public class ListTest {
public static void main(String[] args) {


  List list = new ArrayList();
  list.add(1);
  list.add(1);
  list.add(2);
  list.add(3);
  List newList = ( List)removeDupicateList(list);
  for(Integer i : newList){
  System.out.println(i);
  }

}
/*

* 集合中的元素去重
*/
public static List removeDupicateList(List list){

Set set = new HashSet();
List newList = new ArrayList();
for(Iterator iter = list.iterator();iter.hasNext();){
Object element = iter.next();
if(set.add(element)){
newList.add(element);
}
}

return newList;
}
}




比较两个集合List,返回List b中存在,但list a中不存在的元素
public static > List compareList(List a,List b){

List resultList = new ArrayList();
Map mapA = new HashMap();
Map mapB = new HashMap();

for(T t : a){
mapA.put(t, 1);
}
for(T t : b){
mapB.put(t, 1);
}
Iterator it = mapA.keySet().iterator();
while(it.hasNext()){
T key = (T) it.next();
if(!mapB.containsKey(key)){
resultList.add(key);
}
}
return resultList;
}


你可能感兴趣的:(1)