Collections

Java arraylist sort comparator

package com.candidjava;

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

class Studentdata {
  int rno;
  String name;
  int age;

  // Constructor for Studentdata
  Studentdata(int rno, String name, int age) {
    this.rno = rno;
    this.name = name;
    this.age = age;

  }

  // Used to print studentdetails in main method
  public String toString() {
    return this.rno + " " + this.name + " " + this.age;
  }
}

// This class is for Student name sort
class Namesort implements Comparator<Studentdata> {

  @Override
  public int compare(Studentdata o1, Studentdata o2) {
    return o1.name.compareTo(o2.name);
  }
}

// This class id for Student Roll number sort
class Rollnosort implements Comparator<Studentdata> {

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

public class Arraylistsortcomparator {

  public static void main(String[] args) {
    ArrayList<Studentdata> al = new ArrayList<Studentdata>();
    al.add(new Studentdata(15, "reena", 12));
    al.add(new Studentdata(30, "teena", 24));
    al.add(new Studentdata(21, "meena", 20));
    al.add(new Studentdata(21, "seetha", 20));
    System.out.println("Unsorted Arraylist");
    for (int i = 0; i < al.size(); i++) {
      System.out.println(al.get(i));
    }
    // Ascending Order
    System.out.println("Sorted by Name in Ascending order:");
    Collections.sort(al, new Namesort());
    for (int i = 0; i < al.size(); i++) {
      System.out.println(al.get(i));
    }
    System.out.println("Sorted by Rollno in Ascending order:");
    Collections.sort(al, new Rollnosort());
    for (int i = 0; i < al.size(); i++) {
      System.out.println(al.get(i));
    }

    // Descending order
    System.out.println("Sorted by Name in Descending order:");
    Collections.sort(al, Collections.reverseOrder(new Namesort()));
    for (int i = 0; i < al.size(); i++) {
      System.out.println(al.get(i));
    }
    System.out.println("Sorted by Rollno in Descending order:");
    Collections.sort(al, Collections.reverseOrder(new Rollnosort()));
    for (int i = 0; i < al.size(); i++) {
      System.out.println(al.get(i));
    }

  }
}

OUTPUT

Unsorted Arraylist
15 reena 12
30 teena 24
21 meena 20
21 seetha 20
Sorted by Name in Ascending order:
21 meena 20
15 reena 12
21 seetha 20
30 teena 24
Sorted by Rollno in Ascending order:
15 reena 12
21 meena 20
21 seetha 20
30 teena 24
Sorted by Name in Descending order:
30 teena 24
21 seetha 20
15 reena 12
21 meena 20
Sorted by Rollno in Descending order:
30 teena 24
21 seetha 20
21 meena 20
15 reena 12