Home > front end >  How do you order objects in an arraylist by one parameter then if that parameter is the same order t
How do you order objects in an arraylist by one parameter then if that parameter is the same order t

Time:12-04

So I have an array list with the class players and an object created from a constructor with the parameters players(points, trophy).

ArrayList<players> team = new ArrayList<players>();
players player = new players(15,2);
players player2 = new players(15,5);
players player3 = new players(14,8);
team.add(player);
team.add(player2);
team.add(player3);

I would like to sort by the number of points so that the highest points print first then if the number of points is the same sort those with the same number of points by the number of trophies. I have tried the collections methods like this

Collections.sort(team,Comparator.comparingInt(players::getPoints).reversed())

This managed to print the right order for points but I was unable to sort by trophies if points were the same.

CodePudding user response:

Try this:

Collections.sort(team, Comparator.comparingInt(players::getPoints).thenComparingInt(players::getTrophies).reverse());
  • Related