25 March 2010

Converting a list of Strings into a list of Calendars (using a pattern and a locale)

Valid since: op4j 1.0

Description
Create a List<Calendar> object from a List<String>, by applying a standard Java locale-dependent pattern to each String.

Scenario
We need to build a List of Calendar objects from the values in our dates variable, which contains a couple of Strings representing dates:
// dates == LIST ["12 de octubre, 1492", "06 de diciembre, 1978"]
A valid Java pattern for parsing these dates is "dd 'de' MMMM, yyyy", and we must tell the parser that month names (in long format) are in Spanish.

Recipe
Iterate the list of Strings and execute the FnString.toCalendar(...) function on each element to obtain a Calendar.

As our pattern ("dd 'de' MMMM, yyyy") makes use of textual month names (like jan, may, december...), this function requires a locale to be specified so that the names of the months are correctly understood. In this case, we will specify the Spanish locale (es):

List<Calendar> cals =
    Op.on(dates).map(FnString.toCalendar("dd 'de' MMMM, yyyy", "es")).get();

Comments
This recipe involved mapping (map(...) action), which is equivalent to iterating, then executing, and then ending iteration on an array, list or set. This makes the above example equivalent to:
List<Calendar> cals =
    Op.on(dates).forEach().exec(FnString.toCalendar("dd 'de' MMMM, yyyy", "es")).get();

Let's compare with non-op4j normal Java code:
SimpleDateFormat dateFormat = new SimpleDateFormat(("dd 'de' MMMM, yyyy", "es"));
List<Calendar> cals = new ArrayList<Calendar>();
for (String date : dates) {
    Date dDate = null;
    try {
        dDate = dateFormat.parse(date);
    } catch (ParseException e) {
        throw SomeException(e);
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(dDate);
    cals.add(cal);
}

No comments:

Post a Comment