• Java 各种工具类的使用方法


    1. 属性拷贝 属性名词和类型相同才能拷贝

    import org.springframework.beans.BeanUtils;
    BeanUtils.copyProperties(dto,wmNews); //dto, wmNews 是两个实体类  dto为源对象,wmNews为目标对象
    
    • 1
    • 2

    2. list集合转换为string类型

    import org.apache.commons.lang3.StringUtils;
    String images = StringUtils.join(dto.getImages(), ",");  // 字符串中以 , 进行分割
    
    • 1
    • 2

    3. 将json格式的String类型按照指定格式进行转换

    List mapList = JSON.parseArray(content, Map.class); // 将json格式的String类型按照指定格式进行转换
    
    public List extractUrlInfo(String content){
        List materialList = new ArrayList<>();
        List mapList = JSON.parseArray(content, Map.class); // 将json格式的String类型按照指定格式进行转换
        for (Map map : mapList) {
            if (map.get("type").equals("image")){
                String imageUrl = (String) map.get("value");
                materialList.add(imageUrl);
            }
        }
        return materialList;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    4. 前端将’id1,id2,id3’ 转换成’id1’,‘id2’,‘id3’

    $("#excelExport").click(function() {
    	var rows = $grid.datagrid('getChecked');   // 获取所有勾选的记录
    	var ids = "";
    	if (rows) {
    		$.each(rows, function(index, value) {
    			ids += (value.id + ",")  // 将所有勾选记录的id拼装为字符串, 'id1,id2,id3,'  注意该字符串最后多了一个逗号
    		});
    		if (ids == "") {
    			$.messager.alert("操作提醒", "请先勾选需要导出的记录", "warning");
    		} else {
    			ids = ids.substr(0, ids.length - 1);  // 删除字符串最后一个字符,'id1,id2,id3'
    			let strList = ids.split(',');  // 将字符串进行分隔
    			let idList = "";
    			// 将'id1,id2,id3' 转换成'id1','id2','id3'
    			for (let i = 0; i < strList.length; i++) {
    				idList += ("'"+strList[i]+"'");//拼接单引号,到数据库后台用in查询.
    				if(i!=strList.length-1){//前面的元素后面全拼上",",最后一个元素后不拼
    					idList += (",");
    				}
    			}
    			// 导出功能
    			window.parent.location.href = "${ctx}/change/znAchievementChangeReward/excelExportDetail?ids=" + ids;
    		}
    	} else {
    		$.messager.alert("操作提醒", "请先勾选需要导出的记录", "warning");
    	}
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    5. 将数组 String[] 转换为 List 集合

    /**
    	 * 根据转化项目和奖励年度进行分组    Collectors.groupingBy()
    	 * @param ids  -- 'id1,id2,id3'
    	 * @return
    	 */
    public Map> getRewardGroup(String ids){
    	String[] split = ids.split(",");
    	List resultList=new ArrayList<>(Arrays.asList(split));  // 将数组 String[] 转换为 List 集合
    	List rewards = znAchievementChangeRewardDao.getRewardsByIds(resultList);
    	if (rewards.size() > 0){
    		// 使用stream流进行分组
    		Map> listMap = rewards.stream().collect(
    				Collectors.groupingBy(
    						reward -> reward.getProjectId() + ";" + reward.getRewardYear()
    				)
    		);
    		return listMap;
    	}
    	return null;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    6. oracle 数据库根据某字段和进行排序

    --  zn_score_person  表名称;    SCORE,JOB_NUM 表字段;   dense_rank()  oracle自带排序方法
    SELECT t.*,dense_rank() over(order by t.totalScore desc) rank FROM 
    (SELECT sum(SCORE) as totalScore,JOB_NUM FROM zn_score_person GROUP BY JOB_NUM ORDER BY totalScore DESC) t 
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    7. 提取字符串中的数值

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * 获取字符串中的数值
     */
    public class isNumber {
        public static void main(String[] args) {
            String s = getNumber("92.9%");
            System.out.println(s);
        }
        
        public static String getNumber(String str) {
            String pReg = "(\\d+\\.\\d+)";
            // 控制正则表达式的匹配行为的参数(小数)
            Pattern p = Pattern.compile(pReg);
            //Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
            Matcher m = p.matcher(str);
            //m.find用来判断该字符串中是否含有与"(\\d+\\.\\d+)"相匹配的子串
            if (m.find()) {
                //如果有相匹配的,则判断是否为null操作
                //group()中的参数:0表示匹配整个正则,1表示匹配第一个括号的正则,2表示匹配第二个正则,在这只有一个括号,即1和0是一样的
                str = m.group(1) == null ? "" : m.group(1);
            } else {
                //如果匹配不到小数,就进行整数匹配
                pReg = "(\\d+)";
                p = Pattern.compile(pReg);
                m = p.matcher(str);
                if (m.find()) {
                    //如果有整数相匹配
                    str = m.group(1) == null ? "" : m.group(1);
                } else {
                    //如果没有小数和整数相匹配,即字符串中没有整数和小数,就设为空
                    str = "";
                }
            }
            return str;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    在这里插入图片描述

    8. 前后端传递时间注意事项

    import java.sql.Timestamp;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    import org.kl.bf.entity.Excel;
    import org.kl.bf.entity.AuditableEntityForSaas;
    import com.fasterxml.jackson.annotation.JsonFormat;
    import org.springframework.format.annotation.DateTimeFormat;
    
    /**
     * @author Code Generator
     * @since  2023-02-27 09:13:12
     * @see   ZnNtAchresult
     */
    @Entity
    @Table(name = "zn_nt_achresult")
    public class ZnNtAchresult extends AuditableEntityForSaas {
    	private static final long serialVersionUID = 1L;
    		
    		@Excel(exportName = "成果获得时间")
    		@DateTimeFormat(pattern="yyyy-MM-dd")
    		private Timestamp getTime;
    		
    		public ZnNtAchresult(String id) {
    			this.id = id;
    		}
    
    		@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    		public Timestamp getGetTime() {
    			return getTime;
    		}
    
    		public void setGetTime(Timestamp getTime) {
    			this.getTime = getTime;
    		}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    @DateTimeFormat(pattern=“yyyy-MM-dd”) // 前端传递到后端时间格式化
    @JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+08:00”) // 后端回显到前端显示格式

    9. double 类型数据加减乘除运算

    import java.math.BigDecimal;
    public class DoubleUtil {
        
        private static final int DEF_DIV_SCALE = 5; // 小数点后的保留位数
        
        /**
         * Double精确的加法运算
         * @param d1 被加数
         * @param d2 加数
         * @return 两个参数的和
         */
        public static double add( double d1, double d2 ) {
            BigDecimal value1 = new BigDecimal( Double.toString(d1) );
            BigDecimal value2 = new BigDecimal( Double.toString(d2) );
            return value1.add(value2).doubleValue();
        }
        
        /**
         * Double精确的减法运算
         * @param d1 被减数
         * @param d2 减数
         * @return 两个参数的差
         */
        public static double sub( double d1, double d2 ) {
            BigDecimal value1 = new BigDecimal( Double.toString(d1) );
            BigDecimal value2 = new BigDecimal( Double.toString(d2) );
            return value1.subtract(value2).doubleValue();
        }
        
         /**
          * Double精确的乘法运算
          * @param d1 被乘数
          * @param d2 乘数
          * @return 两个参数的积
          */
        public static Double mul( double d1, double d2 ) {
            BigDecimal value1 = new BigDecimal( Double.toString(d1) );
            BigDecimal value2 = new BigDecimal( Double.toString(d2) );
            return value1.multiply(value2).doubleValue();
        }
        
        /**
          * Double精确的除法运算, 当出现除不尽的情况时, 精确到小数点以后10位, 以后的数字四舍五入
          * @param d1 被除数
          * @param d2 除数
          * @return 两个参数的商
          */
        public static double div( double d1, double d2 ) {
            return div( d1, d2, DEF_DIV_SCALE );
        }
        
        /**
         * Double精确的除法运算, 当出现除不尽的情况时, 精确到小数点以后10位, 以后的数字四舍五入
         * @param d1 被除数
         * @param d2 除数
         * @param scale 表示需要精确到小数点的后几位
         * @return 两个参数的商
         */
        public static double div( double d1, double d2, int scale ) {
            if ( scale < 0 ) {
                throw new IllegalArgumentException( "参数[scale]必须是正整数或者零" );
            }
            BigDecimal value1 = new BigDecimal( Double.toString(d1) );
            BigDecimal value2 = new BigDecimal( Double.toString(d2) );
            return value1.divide( value2, scale, BigDecimal.ROUND_HALF_UP ).doubleValue();
        }
     
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    10.StringUtils 工具类截取字符串

    //与第一种方法效果一样
    StringUtils.substring("hello world", 4);     // 返回值,从第4位截取到字符串末尾 : o wrold
    StringUtils.substring("hello world", 4, 10); // 返回值,从第4位截取到第10位    :   o wrol
    
    //截取某个字符串之前的字符
    StringUtils.substringBefore("hello world", "l"); 
    //结果是:he          这里是以第一个”l”,为标准。
    StringUtils.substringBeforeLast("hello world", "l");
    //结果为:hello wor   这里以最后一个“l”为准。
    
    //截取某个字符串之后的字符
    StringUtils.substringAfter("hello world", "l");
    //结果是:lo world   这里是以第一个”l”,为标准。
    StringUtils.substringAfterLast("hello world", "l");
    //结果为:d          这里以最后一个“l”为准。
    
    //截取两个字符串之间隔的字符
    StringUtils.substringBetween("hello world", "o");    
    //结果是: w   两个o之间的字符串。   
    StringUtils.substringBetween("hello world", "l", "r"); 
    //结果是: lo wo   第一个字符“l”与第一个字符“r”之间的字符串   
    StringUtils.substringsBetween("hello world", "l", "r");
    //结果是:数组 [lo wo]   第一个字符“l”与第一个字符“r”之间的字符串,以数组形式返回。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    雷电模拟器在打开“指针位置“后,无效,没有指针xy轴坐标显示?(解决方法)
    数据思维笔记整理
    独立站SEO推广的正确打开方式
    从国产低代码龙头企业零赛云看零(低)代码在软件开发行业和工业企业的应用趋势
    java计算机毕业设计员工信息管理系统源码+mysql数据库+系统+lw文档+部署
    MQ - 39 Serverless : 基于MQ和Serverless设计事件驱动架构
    【python 】pygame制作简单的游戏移动操作
    java学习第193天,javaWeb学习第52天;p291-300(08/26)-6h,昨天2h
    dreamweaver作业静态HTML网页设计——摩尔庄园7页HTML+CSS+JS DW大学生网页作业制作设计 Dreamweaver简单网页
    HTML5期末大作业:美妆网页主题网站设计——清新的手工肥皂网站展示(4页)HTML+CSS+JavaScript
  • 原文地址:https://blog.csdn.net/xiaotiaoza/article/details/131528180