6

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());
2
  • Might be a good idea to actually convert your String using this defined simpleDateFormat. You filter some stuff and that's all. Here are several examples about type conversion in streams. Commented Oct 14, 2016 at 15:53
  • 1
    map is what you are looking for. Commented Oct 14, 2016 at 15:57

3 Answers 3

10

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]
Sign up to request clarification or add additional context in comments.

1 Comment

why does this not work for the below list?
2

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

4 Comments

Error 1: cannot convert from List<Date> to ArrayList<Date>. Error 2: Unhandled exception type ParseException
Still won't compile.
toList returns List of objects not ArrayList
That's what I get for copying OP ;)
0

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

3 Comments

return null when encountering bad data is likely a bad idea.
Since you're using Java 8 features, is there any reason you're creating an anonymous class, rather than a lambda expression block?
Corrected null. Also, there is no specific reason. I preferred an anonymous class just for the readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.