fork download
  1. import java.time.format.DateTimeFormatter;
  2. import java.time.YearMonth;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.stream.Collectors;
  6. import java.util.stream.Stream;
  7.  
  8. class Main {
  9. public static void main(String[] args) {
  10. Map<String, Long> expectedValues = new HashMap<>();
  11. expectedValues.put("2021-06-01", 10L);
  12. expectedValues.put("2021-07-01", 20L);
  13. expectedValues.put("2021-08-01", 30L);
  14.  
  15. expectedValues = transform(expectedValues);
  16.  
  17. // Show the map, sorted by date
  18. expectedValues.entrySet().stream()
  19. .sorted(Map.Entry.comparingByKey())
  20. .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
  21. }
  22.  
  23. private static Map<String, Long> transform(Map<String, Long> expectedValues) {
  24. DateTimeFormatter format = DateTimeFormatter.ISO_LOCAL_DATE;
  25. return Stream.iterate(YearMonth.now(), ym -> ym.minusMonths(1))
  26. .limit(12)
  27. .map(ym -> ym.atDay(1).format(format))
  28. .map(str -> Map.entry(str, expectedValues.getOrDefault(str, 0L)))
  29. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  30. }
  31. }
Success #stdin #stdout 0.17s 55528KB
stdin
Standard input is empty
stdout
2020-10-01: 0
2020-11-01: 0
2020-12-01: 0
2021-01-01: 0
2021-02-01: 0
2021-03-01: 0
2021-04-01: 0
2021-05-01: 0
2021-06-01: 10
2021-07-01: 20
2021-08-01: 30
2021-09-01: 0