28 March 2010

Sorting an array

Valid since: op4j 1.0

Sort an array using the natural order of their elements.

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

Just apply the sort() action to the array:

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

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);
oceans = oceansList.toArray(new String[oceansList.size()]);

No comments:

Post a Comment