Sorted list of elements within a collection

When doing some actions with the elements of a collection, you may need to sort them by a certain value. 

Working with non-comparable elements

In case there is no need in rearranging elements within a collection, you can use the following AnyLogic functions to get the ordered list, and then work with it in your code.

<T> java.util.List<T> sortAscending( collection, value ) - Returns a new collection with rearranged elements from the given collection sorted by the certain value in the ascending order.

<T> java.util.List<T> sortDescending( collection, value ) - Returns a new collection with rearranged elements from the given collection sorted by the certain value in the descending order.

Examples:

  List sortedByAgeAsc = sortAscending( people, p -> p.age );

  List sortedByIncomeDesc = sortDescending( people, p -> p.income );

Working with comparable elements

Objects in your collection may implement the Comparable interface, which allows comparing them to one another and applying natural sorting to them. The elements of primitive data types (String, Int, Double, etc.) have the Comparable interface already implemented. For complex data types, you need to implement this interface yourself to be able to sort elements.

You can use the following functions for sorting elements within lists that contain comparable elements. All elements in these lists must implement the Comparable interface. Calling these functions implies modifying the list, therefore the specified list must be modifiable.

public static <T extends Comparable<? super T>> void sortAscending( List<T> list ) - Sorts the specified list in ascending order, according to the natural ordering of its elements.

public static <T extends Comparable<? super T>> void sortDescending( List<T> list ) - Sorts the specified list in ascending order, according to the inverted natural ordering of its elements.

Example:

sortAscending( pricesList );

Here we sort the elements of the pricesList list in ascending order (assuming the list contains the values of the Double type, which can be compared directly).