0

I was looking at the page help with the same title as this thread: https://help.anylogic.com/index.jsp?topic=%2Fcom.anylogic.help%2Fhtml%2Fdata%2FSort_Collection.html

As shown in the page, if you want to sort a list in increasing or decreasing order you used sortAscending or sortDescending. In the example included, a list of people is sorted by age or time and by income the other time.

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

What if I want to sort a list by two fields at the same time? Like in this people list I want to sort by ascending income and descending age so the first element of the sorted list to be the oldest person with lowest income. If I run them one after another is the same after just running the second one. I tried to use and operator inside one statement but that didn't work

  • Does this answer your question? [How to sort by two fields in Java?](https://stackoverflow.com/questions/4805606/how-to-sort-by-two-fields-in-java) – Felipe May 01 '20 at 20:08

2 Answers2

1

You need to use Java comparators, see for example Sorting a list in Java using 2 criteria

Here is an example implementing a comparator in AnyLogic code, but only using 1 criteria. It compares agents living in GIS space to the specific location (getXYZ()):

ArrayList<MyAgent> listOfAgents= new ArrayList<MyAgent>(); 
// fill this with agents next

Collections.sort(listOfAgents, new Comparator<MyAgent>() {
    @Override
    public int compare(MyAgent agent1, MyAgent agent2) {
        return Double.compare(main.myGISNetwork.getDistance(agent1.getXYZ(), getXYZ()), main.myGISNetwork.getDistance(agent2.getXYZ(), getXYZ()));` 
    }
});
Benjamin
  • 10,603
  • 3
  • 16
  • 28
0

Try sorting by income first and then age. For all agents with the same age, they will remain sorted by income. It can be counter-intuitive to put your highest priority sort last, but it will give you what you want.

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

Another trick would be to give each agent a score, so that age is weighted way more than income. There are some risks, such as making sure your weighting factor is large enough to overcome your income. I typically do the first approach, but also be careful if your data has age in terms of 30.1 years and 30.2 years. You may want to do some rounding to count those all as 30 years old - depends on your use case.

List sortedByIncomeDesc = sortAscending( people, p -> p.age * 100000000 - p.income );
Amy Brown Greer
  • 706
  • 4
  • 7