28 March 2010

Removing duplicates from an array (or list)

Valid since: op4j 1.0

Description
Remove duplicate elements from an array (or list).

Scenario
We have a String[] capitals variable, such as:
// capitals == ARRAY [ "Lisboa", "Madrid", "Paris", "Lisboa", "Bruxelles" ]
...and we want to remove duplicate elements in order to get:
// capitals == ARRAY [ "Lisboa", "Madrid", "Paris", "Bruxelles" ]

Recipe
Operate on the array and use the distinct() action:

capitals = Op.on(capitals).distinct().get();

Comments
If we had a list instead of an array, our code would have been just the same:
// capitalList == LIST [ "Lisboa", "Madrid", "Paris", "Lisboa", "Bruxelles" ]
capitalList = Op.on(capitalList).distinct().get();

Finally, let's compare with the equivalent non-op4j Java code:
Set<String> capitalSet = new LinkedHashSet<String>();
for (String capital : capitals) {
    capitalSet.add(capital);
}
capitals = capitalSet.toArray(new String[capitalSet.size()]);

No comments:

Post a Comment