25 March 2010

Creating maps by coupling elements

Valid since: op4j 1.0

Description
Create a java.util.Map object by specifying all its keys and values, alternating them into an array, list or set, and then performing the couple action which will consider all even elements as keys and odd elements as values (starting with 0).

Scenario
We want to create a map relating some countries to their capital cities. Like: {{"Spain"="Madrid"}, {"United Kingdom"="London"}, {"France"="Paris"}}.

Recipe
First specify all the keys and values (alternating them in key-value order) and then execute the couple action:

Map<String,String> capitals =
    Op.onListFor("Spain", "Madrid", "United Kingdom", "London", "France", "Paris").couple().get();


Comments
Coupling needs the resulting map to specify the same type for keys and values (e.g. Map<String,String>, Map<Integer,Integer>, etc.).

Comparing it with non-op4j code...
Map<String,String> capitals = new LinkedHashMap<String,String>();
capitals .put("Spain", "Madrid");
capitals .put("United Kingdom", "London");
capitals .put("France", "Paris");

No comments:

Post a Comment