wannaBeDev
wannaBeDev

Reputation: 739

Map stream elements to LocalDate without collecting to list

Suppose I have a stream of Integers representing daily data:

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

where each number belongs to one date starting from 22.01.2020 and I want to get a map Map<LocalDate,Integer>.

So basicaly I need smth like:

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

How do I increment the key (LocalDate) starting at a given date(ex. 22.01.2020)?

Map<LocalDate,Integer> map = Stream.of(12,19,7,13,42,69)
              .collect(Collectors.toMap(x -> **LocalDate.of(2020,1,22)**, x -> x));

Upvotes: 1

Views: 693

Answers (2)

Naman
Naman

Reputation: 31868

A cleaner solution could be to use IntStream such as:

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));

Or if you were stuck with Stream<Integer> as data input using AtomicInteger wouldn't be a bad idea either with a restriction to perform sequential execution:

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);

Upvotes: 3

Jacob G.
Jacob G.

Reputation: 29680

It's slightly difficult to achieve this, mainly because you're working with both a Stream<LocalDate> and a Stream<Integer>. One hack is to store the starting date in a single-element array and modify it inside the 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);

The output of this is:

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

A cleaner solution would be to create a custom Collector so you could support collecting a parallel Stream.

Upvotes: 1

Related Questions