代码之家  ›  专栏  ›  技术社区  ›  wannaBeDev

将流元素映射到LocalDate而不收集到list

  •  0
  • wannaBeDev  · 技术社区  · 4 年前

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

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

    从2020年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
    

    Map<LocalDate,Integer> map = Stream.of(12,19,7,13,42,69)
                  .collect(Collectors.toMap(x -> **LocalDate.of(2020,1,22)**, x -> x));
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Naman    4 年前

    一个更清洁的解决方案是 IntStream 例如:

    LocalDate firstDay = LocalDate.of(2020, Month.JANUARY, 22);
    List<Integer> data = List.of(12, 19, 7, 13, 42, 69);
    Map<LocalDate, Integer> finalMap = IntStream.range(0, data.size())
            .mapToObj(day -> Map.entry(firstDay.plusDays(day), data.get(day)))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

    或者如果你被困在 Stream<Integer> AtomicInteger 对执行顺序执行进行限制也不失为一个坏主意:

    LocalDate firstDay = LocalDate.of(2020, Month.JANUARY, 22);
    AtomicInteger dayCount = new AtomicInteger();
    Map<LocalDate, Integer> finalMap = Stream.of(12, 19, 7, 13, 42, 69)
            .map(data -> Map.entry(firstDay.plusDays(dayCount.getAndIncrement()), data))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    System.out.println(finalMap);
    
        2
  •  1
  •   Jacob G.    4 年前

    实现这一点有点困难,主要是因为您同时使用 Stream<LocalDate> 还有一个 Stream<Integer> . 一 乱劈 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}
    

    收藏家 所以你可以支持收集一个 Stream