JAVA计算最大连续天数

JAVA实现计算最大连续天数 比如连续签到天数 连续参加抽奖天数

    /**
     * 计算最大连续天数
     *
     * @param days
     * @return
     */
    private Integer calcContinuousDay(List<String> days) {
        if (days == null || days.size() == 0) {
            return 0;
        }
        List<LocalDate> localDates = days.stream().map(day -> LocalDate.of(Integer.parseInt(day.substring(0, 4)), Integer.parseInt(day.substring(4, 6)), Integer.parseInt(day.substring(6)))).collect(Collectors.toList());
        int continuousDay = 1, maxContinuousDay = 1;
        for (int i = 0; i < localDates.size() - 1; i++) {
            if (localDates.get(i).plusDays(1).equals(localDates.get(i + 1))) {
                continuousDay++;
            } else {
                maxContinuousDay = Math.max(continuousDay, maxContinuousDay);
                continuousDay = 1;
            }
        }
        return Math.max(continuousDay, maxContinuousDay);
    }

另一种解法 

    /**
     * 计算最大连续天数 哈希表法
     *
     * @param days
     * @return
     */
    private Integer calcContinuousDay2(List<String> days) {
        if (days == null || days.size() == 0) {
            return 0;
        }
        Set<LocalDate> localDates = days.stream().map(day -> LocalDate.of(Integer.parseInt(day.substring(0, 4)), Integer.parseInt(day.substring(4, 6)), Integer.parseInt(day.substring(6)))).collect(Collectors.toSet());
        int longestStreak = 0;
        for (LocalDate date : localDates) {
            if (!localDates.contains(date.minusDays(1))) {
                int currentStreak = 1;
                LocalDate currentDate = date;
                while (localDates.contains(currentDate = currentDate.plusDays(1))) {
                    currentStreak++;
                }
                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }
        return longestStreak;
    }

测试代码

    @Test
    public void testContinuousDay() {
        List<String> days = Arrays.asList("20230914", "20230915", "20230916", "20230918", "20230919", "20230920", "20230921");
        System.out.println(calcContinuousDay(days));
    }

必须先对日期进行排序 举例mysql直接查询参与的天

    <select id="queryLotteryDays" resultType="string">
        select date_format(create_time,'%Y%m%d') `day` from ${tableName} where ... group by `day` order by `day`
    </select>

原文 Java 计算最大连续打卡的日期天数_java写个定时自动补卡记录_大雪冬至的博客-CSDN博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

漠星曜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值