java中常用到的工具类使用

Tool

不定期更新,建议收藏,收录日常所用

1,判断对象是否为空的常用工具类

CollectionUtils.isEmpty(集合)			// package org.spingframework.util;
Objects.nonNull(对象)    				// package java.util;

2,对象和数组的复制

 // 对象
 BeanUtils.copyProperties(数据源, 新对象);		// package org.springframework.beans;

 // 数组
 System.arraycopy(数组1,0,数组2,0,数组1长度)

3,关于拼接字符串去掉最后一个符号的三种方式

 		StringBuffer sb = new StringBuffer();
        for (int i = 1; i < 5; i++) {
            sb.append(i).append(",");
        }
        if (sb.length() > 0){
            // 方式一  这种方式只是看到改后的结果
            System.out.println(sb.substring(0,sb.length()-1));
            // 方式二  这种方式不仅是看到改后结果,还自动进行了赋值
            System.out.println(sb.replace(sb.length()-1,sb.length(),""));
            // 方式三  这种方式不仅是看到改后结果,还自动进行了赋值
            System.out.println(sb.deleteCharAt(sb.length()-1));
        }

4,判断对象值属性不为null并且不为空字符串

  /**
     * 校验对象属性是否都为null
     * @param obj 对象
     * @return
     * @throws Exception
     */
    public static boolean isAllFieldNull(Object obj){
        Class stuCla = (Class) obj.getClass();
        Field[] fs = stuCla.getDeclaredFields();
        boolean flag = true;
        for (Field f : fs) {
            f.setAccessible(true);
            Object val = null;
            try {
                val = f.get(obj);
                if(val!=null&&!"".equals(val)) {
                    flag = false;
                    break;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

5,传入多个不同类型的对象,解析map对象

HashMap parseMap = JSON.parseObject(json, HashMap.class);
List<Student> studentList1 = (List<Student>) parseMap.get("studentList");
for(Student student : studentList1){ // Exception
    System.out.println(student.getId() + " ");
}



@RequestMapping(value = "/saveOrUpdateActuary", method = RequestMethod.POST)
    @ApiOperation(value = "保存或更新精算模型数据")
    public FastResponse<Void> saveOrUpdateActuary(@RequestBody Map<String,Object> models,
                                                  Long[] ids,
                                                  @ModelAttribute ActuaryVersionReq actuaryVersionReq){
        String json1 = JSON.toJSONString(models.get("znjsRegionInfos"));
        String json2 = JSON.toJSONString(models.get("productFormInfos"));
        String json3 = JSON.toJSONString(models.get("cancerAttackInfos"));
        // 解析成List集合
        List<ZnjsRegionInfo> znjsRegionInfos = JSON.parseArray(json1, ZnjsRegionInfo.class);
        List<ProductFormInfo> productFormInfos = JSON.parseArray(json2, ProductFormInfo.class);
        List<CancerAttackInfo> cancerAttackInfos = JSON.parseArray(json3, CancerAttackInfo.class);
        
        znjsCityInfoService.saveOrUpdateCityInfo(znjsRegionInfos);
        productFormInfoService.saveOrUpdateProductFormInfo(productFormInfos);
        choosedDrugInfoService.saveChoosedDrugInfo(ids,actuaryVersionReq);
        cancerAttackInfoService.saveOrUpdateCancerAttackInfo(cancerAttackInfos);
        String result = netFeeInfoService.saveOrUpdateNetFeeInfo();
        return ResponseUtils.success(result);
    }

6,判断对象属性值不为空并且不为null

StrUtil.isNotBlank(对象属性值)		// cn.hutool.core.util.StrUtil;
StringUtils.isNoneBlank(对象属性值)	// org.apache.commons.lang3.StringUtils; 

7,字符串拼接常用方式

+				// + 操作符是比较常用的,都熟悉
StringBuilder.append()	// 效率高,线程不安全 
StringBuffer.append()	// 效率相对较低,线程安全
concat()		// String类的方法
Join()			// String类的方法
StringUtils.join   	// org.apache.commons.lang3.StringUtils	该方法更善于拼接数组中的字符串,并且不用担心 NullPointerException。

8,将字符串不是中文字符的都去掉

String bankName = "中国银行(0001sdf)"
bankName.replaceAll("[^\u4E00-\u9FA5]", "")			// 结果:中国银行

9,去掉字符串的前后中括号[]

// import org.apache.commons.lang3.StringUtils;
String results = "[{"name":"username"}]" 
String strip = StringUtils.strip(results, "[]");	// 结果: {"name":"username"}

// 去除字符所有的[]中括号
String km = "[[2100, 2110], [3100]]";
String rest = km.replaceAll("\\[|\\]", "");  // 结果 2100, 2110, 3100

10,将图片转换成Base64形式

		// 图片地址
  		String imgPath = "C:\\Users\\myqxin\\Desktop\\银行卡.jpg";
        InputStream in = null;
        byte[] data = null;

        try {
            in = new FileInputStream(imgPath);
            data =  new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(data);
        System.out.println(encode);

11,日期转string

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

 LocalDateTime now = LocalDateTime.now(); // 可以获取当前年,当前月的天数值
 String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

12,日期格式化转换

 Date date = new SimpleDateFormat("yyyy年MM月dd日").parse("2021年09月15日");
 String newDate = new SimpleDateFormat("yyyyMMdd").format(date);
 
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String format = dateFormat.format(System.currentTimeMillis());

        String taskTime = "20201216T00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH");
        Date date = sdf.parse(taskTime);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = df.format(date);
        System.out.println("格式化后的时间" + s);  // 格式化后的时间2020-12-16 00:00:00

13,判断两个数组是否存在相同的元素

     	String[] myqxin = {"77","22"};
        String[] arr = {"11","22","55"};
        HashSet<String> set = new HashSet<>(Arrays.asList(myqxin));
        set.retainAll(Arrays.asList(arr));
        if (set.size()>0){
            System.out.println(true);
        }

14,求一个数值的自然对数,与excel的LN函数等效

Math.log(13);

15,截取集合

// start,end分别是第几个到第几个,截取的内容包含前不包含结尾,用下标索引
// 此方法会改变原始list列表,返回的这个子列表的数据其实还是原列表的;也就是说,修改这个子列表,将导致原列表也发生改变
List<HSpecial> hps = hSpecialMapper.getHspecialsByOname(oname);
List<HSpecial> newHps = hps.subList(start, end);

16,解析时间格式为(Thu Mar 18 00:00:00 CST 2021)

 	public static String myqxin(String timeStr){
        Preconditions.checkArgument(StringUtils.isNotBlank(timeStr),"时间参数不能为空");
        String pattern = "EEE MMM dd HH:mm:ss zzz yyyy";
        try {
            Date date = new SimpleDateFormat(pattern, Locale.US).parse(timeStr);
            return DateFormatUtils.format(date,"yyyy-MM-dd");
        } catch (ParseException e) {
            System.out.println("时间解析错误");
        }
        return null;
    }

    public static void main(String[] args) {
        String timeStr = "Thu Mar 18 00:00:00 CST 2021";
        System.err.println(myqxin(timeStr));
    }

17,获取当前时间的前一天

  	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.DAY_OF_MONTH,-1);
        System.err.println(sdf.format(now.getTime()));

18,根据年份获取年份天数

// import java.time.LocalDate;

  public static int getDayNumByYear(int year) {
        if (year == 0) {
            return LocalDate.now().lengthOfYear();
        } else {
            return LocalDate.of(year, 1, 1).lengthOfYear();
        }
    }

19,获取某年某月的天数

	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = sdf.parse("2021-01");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.err.println(actualMaximum);

20,从集合中取出某一个属性值的集合

List<String> orderNoList=list.stream().map(Order::getOrderNo).collect(Collectors.toList());
 System.out.println("输出单号集合:"+orderNoList);

21,根据年月获取当前月份的天数(2021-02)

    /**
     * 根据年月获取天数  2021-02
     *
     * @param timeStamp
     * @return
     */
    public static int getDayNumByYearMonth(String timeStamp) {
        String[] split = timeStamp.split("-");
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(split[0]));
        c.set(Calendar.MONTH, Integer.parseInt(split[1]) - 1);
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

22,对HashMap的key进行排序

 public static LinkedHashMap<String, List<AirQualityRankingResp>> mapSortedByKey(Map<String, List<AirQualityRankingResp>> param) {
        // 分组后根据key正序排列,()LinkedHashMap有序)
        LinkedHashMap<String, List<AirQualityRankingResp>> collect = param.entrySet().stream().sorted(new Comparator<Map.Entry<String, List<AirQualityRankingResp>>>() {
            @Override
            public int compare(Map.Entry<String, List<AirQualityRankingResp>> o1, Map.Entry<String, List<AirQualityRankingResp>> o2) {
                try {
                    Date d1 = new SimpleDateFormat("yyyy-MM").parse(o1.getKey());
                    Date d2 = new SimpleDateFormat("yyyy-MM").parse(o2.getKey());
                    return d1.compareTo(d2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        }).collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));
        return collect;
    }

23,求出一组数中离目标值最近的一个数

   public static double getWind(double x) {
        double[] arr = {0.0, 22.5, 45, 67.5, 90, 112.5, 135, 167.5, 180, 202.5, 225, 247.5, 270, 292.5, 315, 337.5};
        double minDifference = Math.abs(arr[0] - x);
        int minIndex = 0;
        for (int i = 1; i < arr.length; i++) {
            double temp = Math.abs(arr[i] - x);
            if (temp < minDifference) {
                minIndex = i;
                minDifference = temp;
            }
        }
        return arr[minIndex];
    }

24,mysql清掉自增id,重新开始

#删除主键列
ALTER TABLE 表名 DROP 主键;   

#添加主键列并设置为自增
ALTER TABLE 表名 ADD m_id INT(11) PRIMARY KEY AUTO_INCREMENT FIRST;   

25,根据当前时间获取剩余天数

    /***
     * 根据当前日期(支持yyyy-MM-dd || yyyy-MM-dd HH:mm:ss格式)
     * 获取当年剩余天数
     * @param strDate
     * @return
     */
    public static int getsyDayNumBydate(String strDate){
        if(strDate==null || strDate.isEmpty() || strDate.length()<10){
            return -1;
        }
        SimpleDateFormat sm = new SimpleDateFormat(strDate.length()>18?"yyyy-MM-dd HH:mm:ss":"yyyy-MM-dd");
        Date date=null;
        try{
            date=sm.parse(strDate);
        }catch(ParseException ex){
            ex.printStackTrace();
            return -1;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
    }

26,筛选掉集合中不需要的数据

  List<YrstHydrology> hydrologyList = list.stream().map(this::getMapData).filter(Objects::nonNull).collect(Collectors.toList());


    private YrstHydrology getMapData(YrstHydrology yrstHydrology) {
        if (StringUtils.isNotEmpty(yrstHydrology.getLongitude()) &&  StringUtils.isNotEmpty(yrstHydrology.getLatitude())) {
            List<String> list2 = new ArrayList<>();
            list2.add(yrstHydrology.getLongitude());
            list2.add(yrstHydrology.getLatitude());
            yrstHydrology.setLnglat(list2);
            yrstHydrology.setStyle(25);
            return yrstHydrology;
        }
        return null;
    }

27,java实现输入指定日期距离当前已过去多少时间

https://blog.csdn.net/qq_45752401/article/details/125644679?spm=1001.2014.3001.5502

28,控制台打印出JVM参数

 public static void main(String[] args) {
        Properties properties = System.getProperties();
        properties.list(System.out);
    }

29,根据年月获取周六周日时间

public static void main(String[] args) {
        System.err.println(getWeekend("2022-07"));
    }

    public static List getWeekend(String timeStamp) {
        List list = new ArrayList();
        String[] split = timeStamp.split("-");
        String year = split[0];
        String month = split[1];
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Integer.parseInt(year));
        calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        // 设置为当月第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // 当月最大天数
        int daySize = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int i = 0; i < daySize - 1; i++) {
            String days = "";
            //在第一天的基础上加1
            calendar.add(Calendar.DATE, 1);
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            // 1代表周日,7代表周六 判断这是一个星期的第几天从而判断是否是周末
            if (week == Calendar.SATURDAY || week == Calendar.SUNDAY) {
                int ct = calendar.get(Calendar.DAY_OF_MONTH);
                if (ct < 10) {
                    days = "0" + ct;
                } else {
                    days = String.valueOf(ct);
                }
                // 得到当天是一个月的第几天
                list.add(year + "-" + month + "-" + days);
            }
        }
        return list;
    }

在这里插入图片描述

30,根据年月获取当月所有日期集合

   public static void main(String[] args) {
        System.err.println(getMonthDate("2022-07"));
    }

    public static List getMonthDate(String timeStamp){
        List list = new ArrayList();
        String[] split = timeStamp.split("-");
        String year = split[0];
        String month = split[1];
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Integer.parseInt(year));
        calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        int day = calendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            String days = "";
            if (i<10){
                days = "0"+i;
            }else {
                days = String.valueOf(i);
            }
            String aDate = year+"-"+month+"-"+days;
            list.add(aDate);
        }
        return list;
    }

31,修改字符串某个位置的字符

    public static void main(String[] args) {
        String aa = "2022-07-23 23:00:00";
        System.err.println(aa.substring(11,13));
        StringBuilder sb = new StringBuilder(aa);
        sb.replace(11,13,"24");
        System.err.println(sb.toString());
    }

在这里插入图片描述

32,统计时间滑动平均值

需求说明:现在有某一天24小时的数据,但我要计算每八小时统计一次数据结果(平均,和,最大值等)。不是24/8哦,是滑动八小时(就是有0到23点,总共一天24小时的数据。分成这样的形式(0-7、1-8、2-9、3-10、。。。。、16-23),总共17份)。代码实现如下:

/**
 * @author: myqxin
 * @Desc:
 * @create: 2022-07-22 14:24
 **/
public class Myqxin {
    public static void main(String[] args) {
        List<User> data = getData();
        for (User datum : data) {
            System.err.println(datum);
        }
        // 每隔多少滑动
        int f = 8;
        // 统计滑动
        ArrayList<List<User>> slide = new ArrayList<>();
        // 统计滑动最大的的一个
        ArrayList<Double> max = new ArrayList<Double>();
        int j = 0;
        if (j + f <= data.size()) {
            for (; j + f <= data.size(); j++) {
                List<User> subList = data.subList(j, j + f);
                slide.add(subList);
            }
        } else {
            List<User> subList = data.subList(j, data.size());
            slide.add(subList);
        }
        for (int i = 0; i < slide.size(); i++) {
            double listAvg = slide.get(i).stream().mapToInt(User::getValue).average().getAsDouble();
            max.add(listAvg);
        }
        for (Double aDouble : max) {
            System.out.println(aDouble);
        }
    }


    public static List<User> getData(){
        ArrayList<User> list = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            String str = "";
            if (i<10){
                str = "0"+i;
            }else {
                str = i+"";
            }
            list.add(new User("00"+(i+1),"2022-07-22 "+str+":00:00",new Random().nextInt(9)+1));
        }
        return list;
    }
}

在这里插入图片描述

33,使用表达式,将文件内容中的小写字母替换成大写

// 搜索小写字母s
"s(\d+)"
// 替换成大写S
"S$1"

在这里插入图片描述

34,springboot定时任务类

 	@Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private void getHourDate(){
        threadPoolTaskScheduler.schedule(()-> System.out.println("sss"),new CronTrigger("* * * * * *"));
    }

35,从集合中取出满足条件的一条或多条记录

  List<PStep> list = stepService.list(wrapper);
  // 取满足条件的多条记录
  List<Integer> w = list.stream().filter((item) -> item.getPStep().startsWith("W")).map(item -> {
            return Integer.valueOf(item.getPStep().substring(1));
        }).collect(Collectors.toList());


  PStep t = list.stream().filter(item -> item.getPStep().startsWith("T")).findAny().orElse(null);

版权声明:本文为qq_45752401原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。