Collections Sort
To sort a given Array List in Ascending order :
1) Standard Sort : For String Type
2)Custom Sort : For Object Type
Standard Sort
public class sorting {
public static void main(String[] args) {
ArrayList<String> places=new ArrayList<String>();
places.add("bangalore");
places.add("delhi");
places.add("Agra");
System.out.println(places);
Collections.sort(places);
System.out.println(places); //Arrange in Ascending order
}
}
Output:
bangalore,delhi,Agra
Agra,bangalore,delhi
Improved Sort
public class improved_sort {
public static void main(String[] args) {
new test2().start_now();
}
}
//Getter Setter Class
class Student implements Comparable<Student>{
private String name;
public void set_name(String name){
this.name=name;
}
public String get_name(){
return name;
}
public int compareTo(Student o) {
return name.compareTo(o.name);
}
}
class test2{
public void start_now(){
ArrayList<Student> students=new ArrayList<Student>();
Student s1=new Student();
Student s2=new Student();
Student s3=new Student();
s1.set_name("rahul");
s2.set_name("pahul");
s3.set_name("mahul");
students.add(s1);
students.add(s2);
students.add(s3);
for(Student s:students)
System.out.print(s.get_name());
Collections.sort(students);
System.out.print("\n");
for(Student s:students)
System.out.print(s.get_name());
}
}
OutPut :
rahulpahulmahul
mahulpahulrahul
mahulpahulrahul
Custom Sort :
public class custom_sort {public static void main(String[] args) {
testing Test=new testing();
Test.start();
}
}
//Getter , Setter Class to create Animal Object
class Animal{
private String Animal_type;
public void set_Animaltype(String Animal_type){
this.Animal_type=Animal_type;
}
public String get_Animaltype(){
return Animal_type;
}
}
class testing{
public void start(){
ArrayList<Animal> animals=new ArrayList<Animal>();
Animal dog=new Animal();
dog.set_Animaltype("dog");
Animal cat=new Animal();
cat.set_Animaltype("cat");
Animal ant=new Animal();
ant.set_Animaltype("ant");
animals.add(dog);
animals.add(cat);
animals.add(ant);
System.out.print("Before Sorting = ");
for (Animal str:animals)
System.out.print(" "+str.get_Animaltype());
custom_sort sort_logic=new custom_sort();
Collections.sort(animals, sort_logic); //
System.out.print("\nAfter Sorting = ");
for (Animal str:animals)
System.out.print(" "+str.get_Animaltype());
}
//inner class
class custom_sort implements Comparator<Animal>{
public int compare(Animal o1, Animal o2) {
return o1.get_Animaltype().compareTo(o2.get_Animaltype());
}
}
}
OutPut
Before Sorting = dog cat ant
After Sorting = ant cat dog
No comments:
Post a Comment