comparators in java

 


import java.util.*;

public class Comparators {
    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<Person>();
        list.add(new Person("ashwith", 34));
        list.add(new Person("abhi", 20));
        list.add(new Person("bharath", 24));
        list.add(new Person("vinay", 31));

        Collections.sort(list);
        System.out.println(list);
    }
}

class Person implements Comparable<Person> {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int compareTo(Person person) {
        if (this.age == person.age) {
            return 0;
        } else {
            return (this.age < person.age ? -1 : 1);
        }
    }

    public String toString() {
        return this.name + ":" + this.age;
    }

}
DRYRUN:

  1. Initialization:

    • An ArrayList named list is created to store Person objects.
    • Four Person objects are added to the list with names and ages:
      • “ashwith” (age 34)
      • “abhi” (age 20)
      • “bharath” (age 24)
      • “vinay” (age 31)
  2. Sorting:

    • The Collections.sort(list) method is called to sort the list of Person objects.
    • The sorting is based on the compareTo method defined in the Person class.
  3. compareTo Method:

    • The compareTo method compares two Person objects based on their ages.
    • If the ages are equal, it returns 0.
    • Otherwise, it returns -1 if the current person’s age is less than the other person’s age, and 1 otherwise.
  4. Sorting Result:

    • After sorting, the list will be in ascending order of ages.
    • The sorted list will be printed using System.out.println(list).

Let’s apply the sorting logic step by step:

  • Initially, the list contains:

    • “ashwith” (34)
    • “abhi” (20)
    • “bharath” (24)
    • “vinay” (31)
  • Comparing “ashwith” (34) with “abhi” (20):

    • Since 34 > 20, “abhi” comes before “ashwith”.
  • Comparing “abhi” (20) with “bharath” (24):

    • Since 20 < 24, “abhi” remains before “bharath”.
  • Comparing “bharath” (24) with “vinay” (31):

    • Since 24 < 31, “bharath” remains before “vinay”.
  • The sorted list will be:

    • “abhi” (20)
    • “bharath” (24)
    • “vinay” (31)
    • “ashwith” (34)

The output will be:

[abhi:20, bharath:24, vinay:31, ashwith:34

Comments