Java 8: date conversion using stream

I am trying to convert dates dynamically. I tried this method, but it returns to void.

How to make an array an array of objects LocalDate?

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.
+4
source share
1 answer

Use forEachis bad practice for this task: you will need to change the external variable.

What you want is to match each date as a string with an equivalent LocalDate. Therefore, you need an operation map:

LocalDate[] dates = Stream.of(datesStrings)
                          .map(LocalDate::parse)
                          .toArray(LocalDate[]::new);
+11
source

Source: https://habr.com/ru/post/1619032/


All Articles