28 March 2010

Removing duplicates from an array (or list)

Valid since: op4j 1.0

Remove duplicate elements from an array (or list).

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" ]

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

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

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) {
capitals = capitalSet.toArray(new String[capitalSet.size()]);

No comments:

Post a Comment