5

I'm trying to convert dates dynamically. I tried this method but it is returning void.

How to make it an array of LocalDate objects?

String[] datesStrings = {"2015-03-04", "2014-02-01", "2012-03-15"};
LocalDate[] dates = Stream.of(datesStrings)
                          .forEach(a -> LocalDate.parse(a)); // This returns void so I
                                                             // can not assign it.
Tunaki
  • 125,519
  • 44
  • 317
  • 399
Yassin Hajaj
  • 20,892
  • 9
  • 46
  • 83

1 Answers1

13

Using forEach is a bad practice for this task: you would need to mutate an external variable.

What you want is to map each date as a String to its LocalDate equivalent. Hence you want the map operation:

LocalDate[] dates = Stream.of(datesStrings)
                          .map(LocalDate::parse)
                          .toArray(LocalDate[]::new);
Community
  • 1
  • 1
Tunaki
  • 125,519
  • 44
  • 317
  • 399