-1

I want to sort a List that contain an ArrayList , but the sorting should be done by a particular field of the objects stored in the list.

I have a class Championship that contains a List with the teams playing in the Championship. I want to order this list by the ranking atribute so I can display the whole classament.

I have read other questions and answers but the solutions were with the use of compareTo() method of the Comparable interface and as parameters to the method was send 2 objects to be compared. But I want to sort all the objects (teams in the list).

public int ranking() {
        return (won * 2) + tied;
    }

static List<Team> teams = new ArrayList<Team>();

Bogdan
  • 623
  • 5
  • 13
  • I think you'll find multiple answers about this. For example this one https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Tsakiroglou Fotis May 18 '20 at 07:41
  • @TsakiroglouFotis I have read that one but is used also to compare 2 objects. – Bogdan May 18 '20 at 07:45

1 Answers1

1

Hope, this will sort teams according to their ranks.

List<Team> sortedList = teams.stream()
       .sorted( (t1, t2) -> t2.getRanking().compareTo(t1.getRanking()) )
       .collect(Collectors.toList());