28 March 2010

Sorting an array

Valid since: op4j 1.0

Description
Sort an array using the natural order of their elements.

Scenario
Our oceans variable contains an unordered array of Strings with the names of the Earth's oceans:
// oceans == ARRAY [ "Pacific", "Atlantic", "Indian", "Arctic", "Southern" ]
...and we want to order it by Strings' natural order, which is alphabetic:
// oceans == ARRAY [ "Arctic", "Atlantic", "Indian", "Pacific", "Southern" ]

Recipe
Just apply the sort() action to the array:

oceans = Op.on(oceans).sort().get();

Comments
This sort() action can also be applied to lists or sets, and there are variants to sort using a comparator (sort(Comparator)) or even sort by the result of executing a function on the elements (sortBy(IFunction)). Maps can also be ordered by their keys.

Let's have a look at the equivalent non-op4j Java code:
List<String> oceansList = Arrays.asList(oceans);
Collections.sort(oceansList);
oceans = oceansList.toArray(new String[oceansList.size()]);

No comments:

Post a Comment