Pages

Showing posts with label Custom List. Show all posts
Showing posts with label Custom List. Show all posts

Friday, February 1, 2013

Sorting ArrayList (String ArrayList and custom class)

 1. String array List order by... use to Collection.sort(arrayList)..


List<String> arrString = new ArrayList<String>();
  
Collections.sort(arrString, new Comparator<String>(){
      public int compare(String obj1, String obj2)
      {
            // TODO Auto-generated method stub
            return obj1.compareToIgnoreCase(obj2);
      }
});


2. Custom class Array List order by.. use to Collection.sort(arraylist)..


//student.java class define public String object.....

class student 
{
      public String name;
      public int rollno;
      public String phone_no;
}

//ArrayList....


List<student> arrStudent = new ArrayList<student>();
arrStudent.add( new student("dddd",45,"755555"));
arrStudent.add( new student("zzzz",45,"345345"));
arrStudent.add( new student("cccc",45,"888888"));
arrStudent.add( new student("qqqq",1,"123123"));
arrStudent.add( new student("llll",12,"123123"));
arrStudent.add( new student("pppp",65,"123123"));
arrStudent.add( new student("hhhh",4,"123123"));
arrStudent.add( new student("bbbb",78,"123123"));
arrStudent.add( new student("abbb",3,"123123"));

//then i want to order by student name then... use this ..

Collections.sort(arrStudent, new Comparator<student>(){
      public int compare(student obj1, student obj2)
      {
            // TODO Auto-generated method stub
            return obj1.name.compareToIgnoreCase(obj2.name);
      }
});

//Sorting student roll number Ascending Order

 Collections.sort(arrStudent, new Comparator<student>(){
  public int compare(student obj1, student obj2)
  {
    // TODO Auto-generated method stub
    return (obj1.rollno < obj2.rollno) ? -1: (obj1.rollno > obj2.rollno) ? 1:0 ;
  }
}); 


//Sorting student roll number Descending Order

 Collections.sort(arrStudent, new Comparator<student>(){
  public int compare(student obj1, student obj2)
  {
    // TODO Auto-generated method stub
    return (obj1.rollno > obj2.rollno) ? -1: (obj1.rollno > obj2.rollno) ? 1:0 ;
  }
}); 


Other Post

- How to use custom contains method in an ArrayList in android?