Tool
不定期更新,建议收藏,收录日常所用1,判断对象是否为空的常用工具类2,对象和数组的复制3,关于拼接字符串去掉最后一个符号的三种方式4,判断对象值属性不为null并且不为空字符串5,传入多个不同类型的对象,解析map对象6,判断对象属性值不为空并且不为null7,字符串拼接常用方式8,将字符串不是中文字符的都去掉9,去掉字符串的前后中括号[]10,将图片转换成Base64形式11,日期转string12,日期格式化转换13,判断两个数组是否存在相同的元素14,求一个数值的自然对数,与excel的LN函数等效15,截取集合16,解析时间格式为(Thu Mar 18 00:00:00 CST 2021)17,获取当前时间的前一天18,根据年份获取年份天数19,获取某年某月的天数20,从集合中取出某一个属性值的集合21,根据年月获取当前月份的天数(2021-02)22,对HashMap的key进行排序23,求出一组数中离目标值最近的一个数24,mysql清掉自增id,重新开始25,根据当前时间获取剩余天数26,筛选掉集合中不需要的数据27,java实现输入指定日期距离当前已过去多少时间28,控制台打印出JVM参数29,根据年月获取周六周日时间30,根据年月获取当月所有日期集合31,修改字符串某个位置的字符32,统计时间滑动平均值33,使用表达式,将文件内容中的小写字母替换成大写34,springboot定时任务类35,从集合中取出满足条件的一条或多条记录36,mysql使用存储过程批量插入数据37,提取字符串里面的数字38,对集合中的某个属性进行去重
不定期更新,建议收藏,收录日常所用
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 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 studentList1 = (List) parseMap.get("studentList");
for(Student student : studentList1){ // Exception
System.out.println(student.getId() + " ");
}
@RequestMapping(value = "/saveOrUpdateActuary", method = RequestMethod.POST)
@ApiOperation(value = "保存或更新精算模型数据")
public FastResponse saveOrUpdateActuary(@RequestBody Map 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 znjsRegionInfos = JSON.parseArray(json1, ZnjsRegionInfo.class);
List productFormInfos = JSON.parseArray(json2, ProductFormInfo.class);
List 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 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 hps = hSpecialMapper.getHspecialsByOname(oname);
List 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 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 mapSortedByKey(Map param) {
// 分组后根据key正序排列,()LinkedHashMap有序)
LinkedHashMap collect = param.entrySet().stream().sorted(new Comparator() {
@Override
public int compare(Map.Entry o1, Map.Entry 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 |