AnyLogic
Expand
Font size

Sorted list of agents within a population

When doing some actions with agents of some population, you may need to sort them by some value. There is no need in rearranging agents within a population, 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(population, value) — Returns a new list with rearranged agents from the given population sorted ascending by value. <T> java.util.List<T> sortDescending(population, value) — Returns a new list with rearranged agents from the given population sorted descending by value.

Examples:

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

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

Shuffling the items within the list/population

If you need to randomly permute the specified list, use the function void shuffle(java.util.List<?> list). All permutations occur with equal likelihood. This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the ”current position”. Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. This method runs in linear time.

How can we improve this article?