java 自封装实用工具类

1.map转对象大小写可以忽略
2.把对象中的 请选择,转换为空字符串
3.去除字符串中的空格、回车、换行符、制表符等
4.去掉对象内属性为字符串类型中的空白字符
5.实现指定对象的属性设置-保存
6.实现指定对象的属性设置-修改
7.List按照number从大到小排序
8.List按照number从小到大排序
9.List升序
10.List降序
11.去掉字符串后面的0
12.map转实体类
13.List<Map<String, Object>> 排序
14.list根据属性去重
15.List手动分页,page为第几页,limit为每页个数
16.百度地图 Api调用相关的百度AK
17.金额处理
/**
     * map转对象大小写可以忽略
     * @param source
     * @param bean
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T BeanCopys(Map<String,Object> source, Class<T> bean) throws Exception{
        T target =  bean.newInstance();
        //获得该对象属性的集合
        Field[] fields = target.getClass().getDeclaredFields();
        source.forEach((key, value) -> {
            if (value!=null && StringUtils.isNotEmpty(value.toString())){
                for (Field field : fields) {
                    try {
                        //设置成可访问
                        field.setAccessible(true);
                        String fileName = field.getName();
                        if (key.equals(fileName.toLowerCase()) || key.equals(fileName)){
                            if (field.getType().toString().indexOf("String")!=-1){
                                field.set(target, String.valueOf(value));
                            }
                            if (field.getType().toString().indexOf("Integer")!=-1){
                                field.set(target, Integer.parseInt(String.valueOf(value)));
                            }
                            if (field.getType().toString().indexOf("BigDecimal")!=-1){
                                field.set(target, new BigDecimal(String.valueOf(value)));
                            }
                            if (field.getType().toString().indexOf("Double")!=-1){
                                field.set(target, Double.parseDouble(String.valueOf(value)));
                            }
                            if (field.getType().toString().indexOf("Float")!=-1){
                                field.set(target, Float.parseFloat(String.valueOf(value)));
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
        return target;
    }


    /**
     * 把对象中的 请选择,转换为空字符串
     *
     * @param <T> 待转化对象类型
     * @param cls 待转化对象
     * @return 转化好的对象
     */
    public static <T> T noNullStringAttr(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return cls;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if ("请选择".equals(value)) {
                        field.set(cls, "");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

	/**
     * 去除字符串中的空格、回车、换行符、制表符等
     * @param str
     * @return
     */
    public static String replaceSpecialStr(String str) {
        if (StringUtils.isNotBlank(str)) {
            str = str.replaceAll("\\s*|\t|\r|\n", "");
        }
        return str;
    }
    
	/**
     * 去掉对象内属性为字符串类型中的空白字符
     * @param obj
     */
    public static void formatString(Object obj){
        //获得该对象属性的集合
        Field[] fields = obj.getClass().getDeclaredFields();
        //定义变量
        String lod_val;
        //遍历集合
        for (Field field : fields) {
            //判断类型是否是string
            if (field.getType() == String.class) {
                try {
                    //设置成可访问
                    field.setAccessible(true);
                    //获得原数据
                    lod_val = (String) field.get(obj);
                    if(StringUtils.isNotBlank(lod_val)) {
                        //去掉空格
                        field.set(obj, replaceSpecialStr(lod_val));
                    }
                } catch (IllegalAccessException ille) {

                }
            }
        }
    }

	/**
     *实现指定对象的属性设置-保存
     * @param obj
     */
    public static void setBasValue(Object obj,User user){
		//        formatString(obj);
        //获得该对象属性的集合
        Field[] fields = obj.getClass().getDeclaredFields();
        //遍历集合
        Date date = new Date();
        for (Field field : fields) {
            try {
                //设置成可访问
                field.setAccessible(true);
                String fileName = field.getName();
                if ("id".equals(fileName)){
                    field.set(obj, UUIDUtil.randomUUID32());
                }
                if ("deleted".equals(fileName)){
                    field.set(obj, 0);
                }
                if (user!=null){
                    if ("countyCode".equals(fileName)){
                        if (!CollectionUtils.isEmpty(user.getAreadata()) && user.getAreadata().size()>0){
                            field.set(obj, user.getAreadata().get(0).getDataid());
                        }
                    }
					 if ("creator".equals(fileName)){
                        field.set(obj,user.getId());
                    }
                    if ("createrName".equals(fileName)){
                        field.set(obj,user.getUsername());
                    }
                    if ("updator".equals(fileName)){
                        field.set(obj,user.getId());
                    }
                    if ("updaterName".equals(fileName)){
                        field.set(obj,user.getUsername());
                    }
                }
                if ("createDate".equals(fileName)){
                    field.set(obj,date);
                }
                if ("updateDate".equals(fileName)){
                    field.set(obj,date);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *实现指定对象的属性设置-修改
     * @param obj
     */
    public static void updateBasValue(Object obj,User user){
		//        formatString(obj);
        //获得该对象属性的集合
        Field[] fields = obj.getClass().getDeclaredFields();
        //遍历集合
        Date date = new Date();
        for (Field field : fields) {
            try {
                //设置成可访问
                field.setAccessible(true);
                String fileName = field.getName();
                if (user!=null){
                    if ("updator".equals(fileName)){
                        field.set(obj,user.getId());
                    }
                    if ("updater".equals(fileName)){
                        field.set(obj,user.getId());
                    }
                    if ("updaterName".equals(fileName)){
                        field.set(obj,user.getUsername());
                    }
                }
                if ("updateDate".equals(fileName)){
                    field.set(obj,date);
                }
                if ("status".equals(fileName)){
                    field.set(obj,0);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

//List按照number从大到小排序
list.sort(Comparator.comparing(ExperexcWorkDynamicsDTO::getUpdateDate).reversed());
		
//List按照number从小到大排序
list.sort(Comparator.comparing(ExperexcWorkDynamicsDTO::getUpdateDate));

//List升序
list = list.stream().sorted((front, behind) -> front.[0].compareTo(behind[0])).collect(Collectors.toList());
//List降序
list = list.stream().sorted((front, behind) -> behind.[0].compareTo(front[0])).collect(Collectors.toList());

// List<Map<String, Object>> 升序
list2.sort(Comparator.comparingDouble(o -> Double.parseDouble(o.get("plantSpace").toString())));

/**
     * List<Map<String, Object>> 排序
     * @param resultList 源数据
     * @param type  1降序,其它升序
     * @param str 排序的字段
     * @return
     */
    public static List<Map<String, Object>> listMapSort(List<NutMap> resultList,int type,String str){
//        list2.sort(Comparator.comparingDouble(o -> Double.parseDouble(o.get("plantSpace").toString())));//升序
        List<Map<String, Object>> list;
        if (type == 1){
            list = resultList.stream().sorted((e1, e2) -> {
                // 降序
                return -Double.compare((Double) e1.get(str), (Double) e2.get(str));
            }).collect(Collectors.toList());
        }else {
            list = resultList.stream().sorted((e1, e2) -> {
                // 升序
                 return -Double.compare((Double) e1.get(str), (Double) e2.get(str));
            }).collect(Collectors.toList());
        }
        return list;
//        list.forEach(e->{
//            System.out.print(e.get("id") + " ");
//        });
    }

//去掉字符串后面的0
areaCode = areaCode.replaceAll("0+$", "");

//map转实体类
PlantLandRoamVo plantLandRoamVo = JSONObject.parseObject(JSONObject.toJSONString(list.get(i)), PlantLandRoamVo.class);

list<map>根据属性去重:
dataList = dataList.stream().collect(Collectors.collectingAndThen(
		Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> (String) p.get("code")))),ArrayList::new));


//List手动分页,page为第几页,limit为每页个数
    public static List<T> subList(List<T> list, int page, int limit) throws Exception{
        List<T> listSort  = new ArrayList<>();
        int size=list.size();
        int pageStart=page==1?0:(page-1)*limit;//截取的开始位置
        int pageEnd=size<page*limit?size:page*limit;//截取的结束位置
        if(size>pageStart){
            listSort =list.subList(pageStart, pageEnd);
        }
        //总页数
        int totalPage=list.size()/limit;
        return listSort;
    }

/**
     * 百度地图 Api调用相关的百度AK
     */
    public final static String BAIDU_MAP_AK = "H1RLDFX3oib78k9N9ocaB1Ac";
/**
     * 根据详细地址获取经纬度
     * @param address
     * @return
     */
    public static Map<String,String> getLocationByAddress(String address){
        address = address.replaceAll(" ","");
        JSONObject obj = new JSONObject();
        Map<String,String> map = new HashMap<>();
        String url1 = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&coordtype=wgs84ll&ak=" + BAIDU_MAP_AK;
        try {
            String json = loadJSON(url1);
            obj = JSONObject.parseObject(json);
            System.out.println(obj.toString());
            // status:0 成功
            String success="0";
            String status = String.valueOf(obj.get("status"));
            if(success.equals(status)){
                String result = String.valueOf(obj.get("result"));
                JSONObject resultObj = JSONObject.parseObject(result);
                map = (Map<String,String>)resultObj.get("location");
                //JSON字符串转换成Java对象
                // AddressComponent addressComponentInfo = JSONObject.parseObject(addressComponent, AddressComponent.class);
                System.out.println("Location:"+map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("未找到相匹配的经纬度,请检查地址!");
        }
        return map;
    }
    
//金额处理
private Map<String,Object> fundProcessing(BigDecimal val){
        BigDecimal val1 = new BigDecimal(10000);
        BigDecimal val2 = new BigDecimal(100000000);
        Map<String,Object> map = new HashMap<>();
        if (val.compareTo(val1) == -1){
            map.put("type","元");//万元以下
            map.put("val",val);
        }else if ((val.compareTo(val1) == 0 || val.compareTo(val1)==1) && (val.compareTo(val2)==-1)){
            map.put("type","万元");//万元-亿元之间
            map.put("val",val.divide(val1,2,BigDecimal.ROUND_HALF_UP));//元转万元四舍五入保留两位小数
        }else {
            map.put("type","亿元");//亿元以上(包括亿元)
            map.put("val",val.divide(val2,2,BigDecimal.ROUND_HALF_UP));
        }
        return map;
    }