Is there a way to also convert (while streaming and collecting) a List of Strings to a new List of Dates?
My attempt:
I defined a SimpleDateFormat and tried to use that in the follwing code, but I can't get it working all together.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
ArrayList<Date> dateList = stringList.stream()
.filter(s -> s.startsWith("<"))
.collect(Collectors.toList());
Solution
Based on the hints to use map, I got a working solution for now that looks like this. Of course any optimization on this is welcomed!
int year = 2016;
int month = 2;
int day = 15;
final List<LocalDate> dateListEarlier = dateList.stream()
.filter(s -> s.startsWith("<"))
.map(s -> s.substring(1).trim())
.map(s -> LocalDate.parse(s, formatter))
.sorted()
.filter(d -> d.isAfter(LocalDate.of(year, month, day)))
.collect(Collectors.toList());
Since you are using Java8
, you could utilize the new DateTime
API
List<String> dateStrings = Arrays.asList("12.10.2016", "13.10.2016", "14.10.2016");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
List<LocalDate> localDates = dateStrings.stream().map(date -> LocalDate.parse(date, formatter)).collect(Collectors.toList());
System.out.println(localDates);
Ouptut
[2016-10-12, 2016-10-13, 2016-10-14]
Use the map
method.
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
final List<Date> dateList = strings.stream()
.filter(s -> s.startsWith("<"))
.map(s -> {
try {
simpleDateFormat.parse(s));
} catch (final ParseException e) {
throw new RuntimeException("Parse failed", e);
}
}).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With