Sorting a list of objects of user-defined class using Comparator interface

Sorting is vital in every aspect of programming. The java.util.Collections.sort() function can be used to sort the elements of a list of a predefined data type.

The Comparator interface is used to sort list of user defined objects. This interface is present in java.util package. For comparing, compare method of the interface is used. A class implementing the interface will be passed to sort method.

Collections.sort() method call compare method of the classes it is sorting. The  compare method returns -1, 0 or 1 to say if it is less than, equal, or greater to the other. It uses this result to swap the elements.

public void sort(List list, Comparator c): is used to sort the elements of List by the given comparator.

Sort list of objects of user-defined class using Comparator interface in Java- Example

Suppose, we want to sort elements of a Player class based on their score in Java.

The Player class has two data members, score and name. We want to sort the players on the basis of score. The SortbyScore class implements the Comparator interface.



import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class MyComparator {
    public static class Player {
        int score;
        String name;

        public Player(int s, String str) {
            score = s;
            name = str;
        }

    }

    public static class SortbyScore implements Comparator<Player> {

        @Override
        public int compare(Player o1, Player o2) {
            return o1.score - o2.score;
        }
    }

    public static void main(String[] args) {
        ArrayList<Player> al = new ArrayList<>();
        al.add(new Player(54, "Rohit"));
        al.add(new Player(67, "Dhawan"));
        al.add(new Player(101, "Virat"));
        al.add(new Player(34, "Dhoni"));

        Collections.sort(al, new SortbyScore());
        for (int i = 0; i < al.size(); i++) {
            System.out.println(al.get(i).name + " " + al.get(i).score);
        }

    }
}

The Output for this code :

Dhoni 34
Rohit 54
Dhawan 67
Virat 101

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *