31 May 2010

Converting the keys in a map

Valid since: op4j 1.0

Description
Convert all the keys in a map without changing its corresponding values.

Scenario
Our Map<String,String> map variable contains some numbers (as keys) along with their names in English language (as values):
// map == MAP [ {"1", "one"}, {"2", "two"}, {"3", "three"} ]
...but notice that keys are Strings, not real Integer objects, and that is precisely what we want to obtain, a Map<Integer,String> newMap variable like:
// newMap == MAP [ {1, "one"}, {2, "two"}, {3, "three"} ]

Recipe
Using op4j, we can iterate on the map entries, select the keys of these entries to operate on, and then execute a function that will convert the entries from String to Integer:

Map<Integer,String> newMap = 
    Op.on(map).forEachEntry().onKey().exec(FnString.toInteger()).get();

Comments
The onKey() action has of course a value counterpart, onValue(), which you can use just like:
Map<String,String> newMap = 
    Op.on(map).forEachEntry().onValue().exec(FnString.toUpperCase()).get();

No comments:

Post a Comment