skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Sunday, October 28, 2012

Sorting a List in ascending order

Posted by Raju Gupta at 12:00 AM – 0 comments
 
This code snippet sorts a list of objects based on the value of a field of those objects

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Student implements Comparable {

 private String name;
 private String rollNumber;
 private String department;
// Constructor for the class

public Student(String name,String rollNumber,String department){
 this.name = name;
 this.rollNumber = rollNumber;
 this.department = department;
 
} 
 public String getName() {

  return this.name;
 }

 public void setName(String name) {

  this.name = name;
 }

 public String getRollNumber() {

  return rollNumber;
 }

 public void setRollNumber(String rollNumber) {

  this.rollNumber = rollNumber;
 }

 public String getDepartment() {

  return this.department;
 }

 public void setDepartment(String department) {

  this.department = department;
 }

 //This Function is responsible for sorting.
 
 public int compareTo(Object student1) {
  if (!(student1 instanceof Student))
   throw new ClassCastException("A Student object expected.");

  int rollNumb = Integer.parseInt(((Student) student1).getRollNumber());
  int hostObjrollNumb = Integer.parseInt(this.getRollNumber());
  return hostObjrollNumb - rollNumb;

 }

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  List<Student> lstEstDetailsPrio = new ArrayList<Student>();
  
  //Adds data to the objects
  
  Student s1 = new Student("Tom","3","CS");
  Student s2 = new Student("Jerry","1","IT");
  Student s3 = new Student("Merry","4","Electronics");
        
  //Adds objects to the list
  
  lstEstDetailsPrio.add(s1);
  lstEstDetailsPrio.add(s2);
  lstEstDetailsPrio.add(s3);
  
  //Sorts the List
  
  Collections.sort(lstEstDetailsPrio);

 }

}

Labels: ArrayList Examples

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger