public class Student implements Comparable {
private String studentname;
public int studentage;
public Student(String studentname, int studentage) {
this.studentname = studentname;
this.studentage = studentage;
}
@Override
public int compareTo(Object comparestu) {
int compareage=((Student)comparestu).studentage;
/* For Ascending order*/
return this.studentage-compareage;
}
@Override
public String toString() {
return "[ name=" + studentname + ", age=" + studentage + "]";
}
}
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListSorting {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student( "Chaitanya", 26));
arraylist.add(new Student( "Rahul", 24));
arraylist.add(new Student( "Ajeet", 32));
arraylist.add(new Student( "aa", 10));
Collections.sort(arraylist);
for(Student str: arraylist){
System.out.println(str);
}
}
}
ref:
https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/