java小技巧收集

  • 收集从开始时间到结束时间月份指定格式的集合

//效果
//[2023-07, 2023-08, 2023-09, 2023-10, 2023-11, 2023-12, 2024-01, 2024-02, 2024-03, 2024-04, 2024-05, 2024-06, 2024-07]
LocalDateTime endTime = LocalDateTime.now();
LocalDateTime startTime = endTime.minusYears(1);

// 创建一个存储月份字符串的列表
List<String> timeList = new ArrayList<>();
LocalDateTime currentMonth = startTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
while (currentMonth.isBefore(endTime) || currentMonth.equals(endTime)) {
    timeList.add(currentMonth.format(formatter));
    currentMonth = currentMonth.plusMonths(1);
}
LocalDate endTime = LocalDate.now();
LocalDate startTime = endTime.minusYears(1);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN);

List<String> timeList = Stream.iterate(startTime, date -> date.plusMonths(1))
        .limit(ChronoUnit.MONTHS.between(startTime, endTime.plusMonths(1)))
        .map(date -> date.format(formatter))
        .collect(Collectors.toList());
  • 收集月初到今天数字天集合

//[1,2,3,4,5]
DateTime endTime = DateUtil.date();
List<Integer> timeList = IntStream.range(1, endTime.dayOfMonth() + 1)
        .boxed()
        .collect(Collectors.toList());
  • list集合根据属性id去重

List<ControlCarTemp> saveCachedDataList  根据属性id去重
//hutool
List<ControlCarTemp> distinct = CollUtil.distinct(saveCachedDataList, ControlCarTemp::getId, false);
  • list集合根据指定字段排序,属性字段值有null的情况

//List 人员对象集合
List<Person> personList = new ArrayList<>();

personList.add(new Person(1, "王一", 18));
personList.add(new Person(2, null, 19));
personList.add(new Person(3, "王五", 21));
personList.add(new Person(3, "", 21));

//[Person(id=3, name=, age=21), Person(id=1, name=王一, age=18), Person(id=3, name=王五, age=21), Person(id=2, name=null, age=19)]
personList.sort(Comparator.comparing(Person::getName,Comparator.nullsLast(String::compareTo)));


//倒序
Stream.of(3,4,1,2,6,5).sorted(Comparator.reverseOrder()).forEach(System.out::println);
//正序
Stream.of(3,4,1,2,6,5).sorted(Comparator.naturalOrder()).forEach(System.out::println);
  • 将比例转换为百分比格式

String percent = String.format("%.2f%%", ratio * 100);

//double类型 ,使用String.format进行保留两位小数
String formattedNumber = String.format("%.2f", number);
//double类型 ,使用String.format进行百分比后保留两位小数
String formattedPercentage = String.format("%.2f%%", number * 100);
  • 月开始时间,年开始时间

//2024-07-01T00:00
LocalDateTime startTime = LocalDateTime.now().with(LocalTime.MIN).with(TemporalAdjusters.firstDayOfMonth());
//2024-01-01T00:00
LocalDateTime startTime = LocalDateTime.now().with(LocalTime.MIN).with(TemporalAdjusters.firstDayOfYear());

//hutool
//2024-07-01 00:00:00
DateTime startTime = DateUtil.beginOfMonth(DateUtil.date());
//2024-01-01 00:00:00
DateTime startTime = DateUtil.beginOfYear(DateUtil.date());

//上个月开始时间
DateTime lastStartTime = DateUtil.beginOfMonth(DateUtil.lastMonth());
//上个月结束时间
DateTime lastEndTime = DateUtil.endOfMonth(DateUtil.lastMonth());

//上一年
DateTime lastStartTime = DateUtil.beginOfYear(DateUtil.offset(DateUtil.date(), DateField.YEAR, -1));
DateTime lastEndTime = DateUtil.endOfYear(DateUtil.offset(DateUtil.date(), DateField.YEAR, -1));
  • 一个表的外键是有多个值组成,并由逗号分隔,如何查询包含外键值行?

-- pgsql:
SELECT * FROM warn_handle WHERE ',' || handle_user || ',' LIKE '%,15340,%';

QueryWrapper<WarnHandle> wrapper = new QueryWrapper<>();
wrapper.apply("',' || handle_user || ',' LIKE CONCAT('%,', {0}, ',%')", userId);
  • 日期格式化类,提供常用的日期格式化对象

//hutool
DatePattern.java

public static final String NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
  • 远程调用

//hutool
String responseText = HttpUtil.post(url, json);

HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
String result3 = HttpUtil.get(checkpointDeleteUrl, paramMap);
  • 生成随机整数

//生成一个大于等于 0 且小于 10 的随机整数,即在范围 [0, 10) 内的整数。
int i = ThreadLocalRandom.current().nextInt(10);

//[42, 22, 2, 70, 77]
//0~100之间的5个随机数
IntStream ints3 = ThreadLocalRandom.current().ints(5, 0, 100);
List<Integer> collect1 = ints3.boxed().collect(Collectors.toList());

@SneakyThrows + Files.lines + try-with-resources

//@SneakyThrows 是 Lombok 提供的一个注解,用于在方法上自动抛出异常。使用 @SneakyThrows 注解可以使方法在遇到异常时,自动将异常转换为 java.lang.RuntimeException 并抛出,而无需显式地在方法中编写异常处理代码
//@SneakyThrows 是 Lombok 提供的一个注解,用于简化在方法中抛出受检查异常的操作。在 Java 中,受检查异常必须显式地在方法签名中声明或者使用 try-catch 块捕获,否则会导致编译错误。
@Test
@SneakyThrows
void file() {
    Stream<String> lines = Files.lines(Paths.get("D:\\button2.txt"));
    lines.forEach(System.out::println);
}


//try-with-resources 是 Java 7 中引入的一种语法结构,用于自动关闭实现了 AutoCloseable 或 Closeable 接口的资源,例如文件流、数据库连接等
@Test
void fileTryWithResources() {
    try (Stream<String> lines = Files.lines(Paths.get("D:\\button2.txt"))) {
        lines.forEach(System.out::println);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

// Files.lines(Paths.get("D:\\button2.txt")) 方法签名
public static Stream<String> lines(Path path) throws IOException {
  return lines(path, StandardCharsets.UTF_8);
}


//读文件后写文件
@Test
void fileReadOrWrite() {
    Path inputFile = Paths.get("D:\\button.txt");
    Path outputFile = Paths.get("D:\\button.bat");

    // 检查输入文件是否存在
    if (!Files.exists(inputFile)) {
        throw new IllegalArgumentException("Input file does not exist: " + inputFile);
    }

    try (Stream<String> lines = Files.lines(inputFile);
         BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {

        lines.forEach(line -> {
            try {
                writer.write(line);
                writer.newLine();
            } catch (IOException e) {
                throw new UncheckedIOException("Error writing line to file", e);
            }
        });

    } catch (IOException e) {
        throw new UncheckedIOException("Error reading or writing file", e);
    }
}

POSTGRESQL中ON CONFLICT的使用

POSTGRESQL中ON CONFLICT的使用-CSDN博客

//如果你不想在发生冲突时执行任何操作,可以使用 DO NOTHING。这样,
//如果插入的数据违反了唯一性约束,PostgreSQL 会忽略这个插入,并且不会报错。

@Insert("insert into control_checkpoint (code ,status,type,create_user,create_user_name,dept_id) " +
        "values (#{code},#{status},#{type},#{createUser},#{createUserName},#{deptId}) " +
        "on conflict on constraint uk_control_checkpoint_code_user_dept do nothing")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertConflict(ControlCheckpoint controlCheckpoint);

//更新操作
INSERT INTO samples (sample_id_lims, data_field1, data_field2)
VALUES ('123', 'New Data 1', 'New Data 2')
ON CONFLICT (sample_id_lims) DO UPDATE
SET data_field1 = EXCLUDED.data_field1,
    data_field2 = EXCLUDED.data_field2;

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值