首页 > 解决方案 > 行之间的scala循环

问题描述

我有这样的事情:

NonWorkingDays =Seq(("2021-01-01"),("2021-01-02"),("2021-01-03"),("2021-01-06"),("2021-01-09"),
                    ("2021-01-10"),("2021-01-16"),("2021-01-17"),("2021-01-23"),("2021-01-24"),
                    ("2021-01-30"),("2021-01-31")).toDF("festivos")

东风:

|Starts     |  End     |Resta|
+-----------+----------+-----+
| 2021-01-04|2021-01-05|    1|
| 2021-01-11|2021-01-14|    3|
+-----------+----------+-----+

如何在 Starts > End 之间进行循环?我的意思是:

for (a <- "2021-01-04" to "2021-01-10") println(a)

标签: scaladateiso8601

解决方案


I do not know Scala but I believe anyone who knows Scala also knows Java. Given below is how it can be done in Java:

import java.time.LocalDate;
import java.time.Period;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<LocalDate> nonWorkingDays = Stream
                .of("2021-01-01", "2021-01-02", "2021-01-03", "2021-01-06", "2021-01-09", "2021-01-10", "2021-01-16",
                        "2021-01-17", "2021-01-23", "2021-01-24", "2021-01-30", "2021-01-31")
                .map(LocalDate::parse)          // LocalDate#parse
                .sorted()                       // Remove it if you do not need to sort the list
                .collect(Collectors.toList());

        for (int i = 0; !nonWorkingDays.get(i).isAfter(LocalDate.parse("2021-01-10")); i++) {
            System.out.println(nonWorkingDays.get(i));
        }

        // Days between 2021-01-11 and 2021-01-14
        int days = Period.between(LocalDate.parse("2021-01-11"), LocalDate.parse("2021-01-14")).getDays();
        System.out.println(days);
    }
}

Output:

2021-01-01
2021-01-02
2021-01-03
2021-01-06
2021-01-09
2021-01-10
3

推荐阅读