Using the interface Comparable we Sort the name in the Student Class.
Ex:
package com.learn;
public class Student implements Comparable<Student>{
private int sno;
private String sname;
public int compareTo(Student other) {
return sname.compareTo(other.sname);
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
Main Program
package com.learn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> normalOrder = new ArrayList<Student>();
Student st= new Student();
st.setSname("Rahim");
st.setSno(101);
Student st1= new Student();
st1.setSname("John");
st1.setSno(102);
Student st2= new Student();
st2.setSname("Ram");
st2.setSno(103);
normalOrder.add(st);
normalOrder.add(st1);
normalOrder.add(st2);
Collections.sort(normalOrder);
System.out.println(normalOrder.get(0).getSname());
System.out.println(normalOrder.get(1).getSname());
System.out.println(normalOrder.get(2).getSname());
}
}
the O/P for the above Program is :
John
Rahim
Ram
0 Response to "Sorting the Arraylist on the basis of the property in the Object"
Post a Comment