Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : Convert dates using stream

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.
like image 497
Yassin Hajaj Avatar asked Dec 08 '15 12:12

Yassin Hajaj


1 Answers

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);
like image 54
Tunaki Avatar answered Nov 15 '22 06:11

Tunaki