11 December 2010

Convert a List<String> to a List<DateMidnight>

Valid since: op4j 1.1

Description
Convert a List<String> where each string represents a date in the format MM/dd/yyyy to a List<DateMidnight>

Scenario
Our List<String> list variable contains strings in the format MM/dd/yyyy:

List<String> list = new ArrayList<String>();
list.add("12/24/2000");
list.add("02/02/2010");
list.add("04/04/2002");
list.add("11/22/2005");
list.add("02/07/2005");
list.add("03/05/2005");
list.add("09/13/2006");
list.add("12/29/2007");

We want to create a List<DateMidNight> with the strings in our list converted
to DateMidnight:

List<DateMidnight> result = new ArrayList<DateMidnight>();
result.add(new DateMidnight(2000, 12, 24));
result.add(new DateMidnight(2010, 2, 2));
result.add(new DateMidnight(2002, 4, 4));
result.add(new DateMidnight(2005, 11, 22));
result.add(new DateMidnight(2005, 2, 7));
result.add(new DateMidnight(2005, 3, 5));
result.add(new DateMidnight(2006, 9, 13));
result.add(new DateMidnight(2007, 12, 29));

Recipe
Steps:
1. Iterate the list and convert each string to DateMidnight.

op4j-jodatime functions involved:
  • FnDateMidnight.strToDateMidnight(pattern): it converts the input string to DateMidnight using the given pattern

Let's see it coded with op4j:

String pattern = "MM/dd/yyyy";
List<DateMidnight> datemidnights = Op.on(list).forEach()
.exec(FnDateMidnight.strToDateMidnight(pattern)).get();

No comments:

Post a Comment