JavaWeb-常用方法

本文介绍了Java编程中的MD5加密、对象属性拷贝、自定义JSON数据处理、字符格式转换(如字符串与JSON、数组、字符等),以及日期相关操作(如获取开始结束时间、时间间隔计算和LocalDateTime处理)和List集合的高级用法,包括求和、判断非空、流式操作和字节大小转换。
摘要由CSDN通过智能技术生成


1、MD5加密

import org.junit.jupiter.api.Test;
import org.springframework.util.DigestUtils;

public class Demo {
    @Test
    public void testMD5(){
        String pwd = "123456";
        String hex = DigestUtils.md5DigestAsHex(pwd.getBytes());
        System.out.println(hex);
    }
}

在这里插入图片描述

2、对象属性拷贝

将DTO中的数据拷贝到Entity中,注意:使用对象拷贝字段属性名要保持一致

import org.springframework.beans.BeanUtils;

BeanUtils.copyProperties(source, target);

4、 自定义JSON数据

使用alibaba包下的JSONObject自定义JSON数据

import com.alibaba.fastjson.JSONObject;

JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "root");
jsonObject.put("password", "123456");

3、字符格式转化

3.1、字符串与JSON格式转换

{
	"username": "root",
	"password": "root"
}
import com.alibaba.fastjson.JSON;

// string ---> json
JSONObject jsonObject = JSON.parseObject(jsonStr);

String username= jsonObject.getString("username");
String password= jsonObject.getString("password");

// json ---> string
String jsonString = JSON.toJSONString(jsonObject);

3.2、字符串与数组格式转换

String str = "D:\\repo\\JavaDemo\\FileTransfer\\static\\client\\v1";

// string --> 数组
String[] split = str.split("\\\\");

// 数组 ---> string
String join = StringUtils.join(Arrays.asList(split), "\\\\");
System.out.println(join);

3.3、字符串与字符格式转换

String str = "人生苦短,我用Java.py";

// string ---> char[]
char[] chars = str.toCharArray();

// char[] ---> string
String string1 = new String(chars);
String string2 = String.valueOf(chars);

3.4、字符串与集合格式转换

import org.apache.commons.lang3.StringUtils;

String str = "2021,2022,2023,2024";

 // string ---> list
 List<String> strings = Arrays.asList(str.split(","));
 System.out.println(strings);

 // list ---> string
 String data = StringUtils.join(strings, ",");
 System.out.println(data);

3.5、字符串与时间格式转换

// string ---> LocalDate
LocalDate beginTime = LocalDate.parse("2024-01-01");

// LocalDate ---> string 
String endTime = String.valueOf(LocalDate.now());

// LocalDateTime ---> string 
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
String dateStr = localDateTime.format(fmt);

// string ---> LocalDateTime 
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateStr = "2021-08-19 15:11:30";
LocalDateTime date2 = LocalDateTime.parse(dateStr, fmt);

4、日期相关计算

4.1、根据当前日期获取开始和结束时间

应用场景:获取当天的全部数据
select * from user where time > beginTime and time < endTime

LocalDate date = LocalDate.now();
log.info("当前时间:" + date);
LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
log.info("这一天的开始时间:" + beginTime);
LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
log.info("这一天的结束时间:" + endTime);

在这里插入图片描述

4.2、根据开始和结束日期获取中间日期

LocalDate beginTime = LocalDate.parse("2024-01-01");
LocalDate endTime = LocalDate.now();

ArrayList<LocalDate> dateList = new ArrayList<>();
dateList.add(beginTime);

while (!beginTime.equals(endTime)) {
    beginTime = beginTime.plusDays(1);
    dateList.add(beginTime);
}

log.info("时间间隔:" + dateList);

在这里插入图片描述

4.3、LocalDateTime日期比较

//获取当前时间
LocalDateTime nowTime= LocalDateTime.now();
//自定义时间
LocalDateTime endTime = LocalDateTime.of(2024, 1, 26, 14, 10, 10);
//比较  如今的时间 在 设定的时间 之后  返回的类型是Boolean类型
System.out.println(nowTime.isAfter(endTime));
//比较   如今的时间 在 设定的时间 之前  返回的类型是Boolean类型
System.out.println(nowTime.isBefore(endTime));
//比较   如今的时间 和 设定的时候  相等  返回类型是Boolean类型
System.out.println(nowTime.equals(endTime));

4.4、Long类型的时间戳转LocalDateTime

Long time = 1653028357000L;
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneOffset.of("+8"));
System.out.println(localDateTime);

5、 List集合

5.1 计算集合数据的总和

ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    list.add(i);
}

Integer sum = list.stream().reduce(Integer::sum).get();
log.info("总和:" + sum);

5.2 条件判断:检测集合是否为空

import cn.hutool.core.collection.CollUtil;

CollUtil.isEmpty(user)  // 判断集合是否为空

5.3 使用stream流获取集合对象的值

List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    users.add(User.builder().name("张三" + i).age(i).gender(i).phone("180000000000").build());
}
System.out.println(users);

// 通过stream流获取列表对象的值
List<String> userNames = users.stream().map(User::getName).collect(Collectors.toList());
System.out.println(userNames);

5.3 使用stream流对集合对象进行分组

List<User> users = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    users.add(User.builder().id(1L).name("张三" + i).age(i).gender(i).phone("180000000000").build());
}
for (int i = 0; i < 2; i++) {
    users.add(User.builder().id(2L).name("张三" + i).age(i).gender(i).phone("180000000000").build());
}
System.out.println(users);
// 通过stream流对列表对象进行分组 ---> 分组之后MapKey=分组条件,MapValue=List<对象>
Map<Long, List<User>> userMap = users.stream().collect(Collectors.groupingBy(User::getId));
System.out.println(userMap);

// {1=[User(id=1, name=张三0, age=0, gender=0, phone=180000000000), User(id=1, name=张三1, age=1, gender=1, phone=180000000000), User(id=1, name=张三2, age=2, gender=2, phone=180000000000)], 2=[User(id=2, name=张三0, age=0, gender=0, phone=180000000000), User(id=2, name=张三1, age=1, gender=1, phone=180000000000)]}

5.4 使用stream流对集合进行排序

正序

list.stream().sorted(Comparator.comparing(FileMigrationVO::getFileLastModified)).collect(Collectors.toList());

倒叙

list.stream().sorted(Comparator.comparing(FileMigrationVO::getFileLastModified).reversed()).collect(Collectors.toList());

6、 将字节大小转换为KB,MB,GB,并保留两位小数

public void setSize() {
    Long size = 1705230L;
    //获取到的size为:1705230
    int GB = 1024 * 1024 * 1024;//定义GB的计算常量
    int MB = 1024 * 1024;//定义MB的计算常量
    int KB = 1024;//定义KB的计算常量
    DecimalFormat df = new DecimalFormat("0.00");//格式化小数
    String resultSize = "";
    if (size / GB >= 1) {
        //如果当前Byte的值大于等于1GB
        resultSize = df.format(size / (float) GB) + "GB   ";
    } else if (size / MB >= 1) {
        //如果当前Byte的值大于等于1MB
        resultSize = df.format(size / (float) MB) + "MB   ";
    } else if (size / KB >= 1) {
        //如果当前Byte的值大于等于1KB
        resultSize = df.format(size / (float) KB) + "KB   ";
    } else {
        resultSize = size + "B   ";
    }
    System.out.println(resultSize);
}

7、 Long类型数据的比较

Objects.equals(Long l1, Long l2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Monly21

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值