将流元素映射到LocalDate而不收集到列表中

问题描述 投票:0回答:2

假设我有代表每日数据的整数流:

Stream.of(12,19,7,13,42,69);

其中每个数字都属于从22年1月22日开始的一个日期,我想获取一张地图Map<LocalDate,Integer>

所以基本上我需要像这样的东西:

22.01.2020  = 12
23.01.2020  = 19
24.01.2020  = 7
25.01.2020  = 13
26.01.2020  = 42
27.01.2020  = 69

如何从给定日期(例如,2020年1月22日)开始增加密钥(LocalDate)?

Map<LocalDate,Integer> map = Stream.of(12,19,7,13,42,69)
                                   .collect(Collectors.toMap(x -> **LocalDate.of(2020,1,22)**, x -> x));
java stream localdate
2个回答
0
投票

您可以简单地使用addDays方法:

LocalDate localDate = new LocalDate("2020-01-22");
LocalDate nextDay = localDate.addDays(1);

不确定将密钥作为LocalDate时在您的上下文中如何工作,您是否只需要检索密钥和一天的时间呢?


0
投票

很难做到这一点,主要是因为您同时使用了Stream<LocalDate>Stream<Integer>。一种hack是将开始日期存储在一个单元素数组中,并在Collector中对其进行修改:

LocalDate[] startDate = { LocalDate.of(2020, Month.JANUARY, 21) };

Map<LocalDate, Integer> map = Stream.of(12, 19, 7, 13, 42, 69)
    .collect(Collectors.toMap(x -> {
        startDate[0] = startDate[0].plusDays(1L);
        return startDate[0];
    }, Function.identity()));

System.out.println(map);

此输出为:

{2020-01-27=69, 2020-01-26=42, 2020-01-25=13, 2020-01-24=7, 2020-01-23=19, 2020-01-22=12}

更干净的解决方案是创建自定义Collector


-1
投票

您可以这样做,

List<Integer> numbers = Arrays.asList(12, 19, 7, 13, 42, 69);
LocalDate startDate = LocalDate.of(2020, 1, 22);

Map<LocalDate, Integer> result = IntStream.range(0, numbers.size()).boxed()
    .collect(Collectors.toMap(n -> startDate.plusDays(n), numbers::get));
© www.soinside.com 2019 - 2024. All rights reserved.