You can sort the collections based on your requirements.
If the input objects for collections is implementing the Comparable interface like String, Integer, Double classes, then you can directly use Collections.sort() method from Collections util class
List<String> al = new ArrayList<>();
al.add("Hyderabad");
al.add("Karachi");
al.add("Abtabad");
al.add("AzadKashmir");
al.add("Udupi");
al.add("Jammu");
Collections.sort(al);
Or you can sort the list based on your requirement.(Reverse alphabetical Order)
Collections.sort(al, (str1, str2) -> str2.compareTo(str1));
If you don't want to use the Collections class, then directly use the sort() method present in List interface.
i. Albhabetical Order
al.sort((str1, str2) -> str1.compareTo(str1));
ii. Reverse Albhabetical Order
al.sort((str1, str2) -> str2.compareTo(str1));
The above solution is for the Objects where the class implements the Comparable Interface like String, Integer, Double, etc...
When to sort the Custom Classes, you need to implement sort by Comparator class or Lambda expression for the Comparator.
Consider you have a Student Class, and need to sort by city names. You can use below code.
Student Class
public class Student {
private String name;
private String city;
public Student() {}
public Student(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Student -> [name=" + name + ", city=" + city + "]";
}
}
Sorting By Collection Class sort() method
Student st1 = new Student("Samir", "Hyderabad");
Student st2 = new Student("Akbar", "Karachi");
Student st3 = new Student("Ramu", "Abtabad");
Student st4 = new Student("Rahim", "AzadKashmir");
Student st5 = new Student("Sardar", "Udupi");
Student st6 = new Student("Fahad khan", "Jammu");
List<Student> al2 = new ArrayList<>();
al2.add(st1);
al2.add(st2);
al2.add(st3);
al2.add(st4);
al2.add(st5);
al2.add(st6);
//Alphabetical Order
Collections.sort(al2, (std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
Collections.sort(al2, (std1, std2) -> std2.getCity().compareTo(std1.getCity()));
By using List.sort() method
//Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));