Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Java 8 - How to convert while streaming a String List to a Date List

Tags:

java

lambda

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());
like image 504
oldsport Avatar asked Oct 14 '16 15:10

oldsport


Video Answer


2 Answers

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]
like image 188
Saravana Avatar answered Oct 13 '22 00:10

Saravana


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());
like image 26
Tobb Avatar answered Oct 13 '22 00:10

Tobb