You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 8实现按日期筛选指定币种最新时间戳数据

需求:按币种获取每日最新时间戳的数据

我需要用Java 8实现:查询指定币种(比如USD)时,获取该币种下每日最新时间戳的所有数据。

实体类定义

class Currency{
   private Integer id;
   private String name;
   private LocalDateTime lastReceived;
   // 省略getter/setter方法
}

数据库原始数据

ID NAME  LAST_RECEIVED
-- ----  -------------
1  USD   18-MAY-22 09.04.01.545899000 AM
2  USD   18-MAY-22 08.04.01.545899000 AM
3  USD   19-MAY-22 08.04.01.545899000 AM
4  USD   20-MAY-22 08.04.01.545899000 AM
5  USD   20-MAY-22 11.04.01.545899000 AM
6  BUSD   18-MAY-22 08.04.01.545899000 AM

期望结果

ID NAME  LAST_RECEIVED
-- ----  -------------
1  USD   18-MAY-22 09.04.01.545899000 AM
3  USD   19-MAY-22 08.04.01.545899000 AM
5  USD   20-MAY-22 11.04.01.545899000 AM

当前问题

我写了排序代码,但只能实现整体排序,没法按日期分组取每日最新数据:

List<Currency> listCurrency = repo.getAllDataBasedOnCurrency("USD");

listCurrency.stream().sorted(Comparator.comparing(Currency::getLastReceived).reversed()).collect(Collectors.toList());
// 我需要的是单日的最新接收数据

解决方案

核心思路是按日期(仅年月日)分组,每组内筛选出lastReceived最新的那条数据,最后把各组结果收集成列表。

实现代码

List<Currency> listCurrency = repo.getAllDataBasedOnCurrency("USD");

List<Currency> dailyLatest = listCurrency.stream()
    // 按日期(LocalDate)分组,key为日期,value为当天所有Currency数据
    .collect(Collectors.groupingBy(
        currency -> currency.getLastReceived().toLocalDate(),
        // 每组内取lastReceived时间最大的元素,再转换为非Optional类型
        Collectors.collectingAndThen(
            Collectors.maxBy(Comparator.comparing(Currency::getLastReceived)),
            Optional::get
        )
    ))
    // 提取分组后的所有结果值
    .values()
    .stream()
    // 可选:按日期排序,让结果与期望顺序一致
    .sorted(Comparator.comparing(c -> c.getLastReceived().toLocalDate()))
    .collect(Collectors.toList());

代码解释

  1. 分组逻辑:通过Collectors.groupingBy将同一天的Currency数据归为一组,分组依据是LocalDateTime转换后的LocalDate(仅保留年月日)。
  2. 组内筛选:每组使用Collectors.maxBy找出lastReceived时间戳最大的元素,再通过collectingAndThen将Optional包装的结果转换为实际的Currency对象(每组至少有一条数据,不会出现空值)。
  3. 结果整理:提取分组后的所有结果,可选按日期排序后收集为最终列表。

内容的提问来源于stack exchange,提问作者Codinghubby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:10:23