简体   繁体   中英

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

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());

All you need to do is to write a function that maps String to Date object, see below:

public static void main(String[] args) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
    List<String> stringList = new ArrayList<>();
    stringList.add("10.10.2014");

    Function<String, Date> function = new Function<String, Date>() {

        @Override
        public Date apply(String s) {
            try {
                return simpleDateFormat.parse(s);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    };

    List<Date> collect = stringList.stream().map(function).collect(Collectors.<Date>toList());

    System.out.println(collect);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM