Sortable

  • Use java.util.Collections.sort(list) for natural sorting(ascending order) for List collection.
  • public interface Comparable Details

    	public interface Comparable< T> {
    		int compareTo(T o);
    	}
  • java.lang package
  • This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
  • It is strongly recommended (though not required) that natural orderings be consistent with equals.
  • String class and Wrapper classes implements Comparable interface by default. So if you store the objects of string or wrapper classes in list, set or map, it will be Comparable by default.
  • Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc.
  • public interface Comparator Details

    	public interface Comparator< T> {
    		int compare(T o1, T o2);
    	}
  • java.util package
  • Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.
  • a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
  • A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.
  • Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
  • Examples

  • Example of sorting an ArrayList in Ascending and Descending order using Collections class.
  • 	import java.util.ArrayList;
    	import java.util.Collections;
    
    	public class SortExample {
    
    		public static void main(String[] args) {
    			//' Create a list of strings
    			ArrayList< String> list = new ArrayList< String>();
    			list.add("Java Refresh");
    			list.add("to");
    			list.add("refresh");
    			list.add("Java");
    			list.add("Skills");
    
    			// By Ascending order
    			Collections.sort(list);
    
    			// List after the use of Collection.sort()
    			System.out.println("Ascending order List :" + list);
    			
    			// By Descending order
    			Collections.sort(list, Collections.reverseOrder());
    
    			// List after the use of Collection.sort()
    			System.out.println("Descending order List :" + list);
    		}
    	}
    	
    - Output
    	Ascending order List :[Java, Java Refresh, Skills, refresh, to]
    	Descending order List :[to, refresh, Skills, Java Refresh, Java]
    	
  • Example of primitive data type sorting (How to sort primitive data type?)
  • 	import java.util.Arrays;
    
    	public class PrimitiveSort {
    
    		public static void main(String[] args) {
    			// create an array of int
    			int numbers[] = { 3, 4, 1 };
    
    			for (int i = 0; i < numbers.length; i++) {
    				System.out.println("Before Sort =" + numbers[i]);
    			}
    			Arrays.sort(numbers);
    
    			for (int i = 0; i < numbers.length; i++) {
    				System.out.println("After Sort =" + numbers[i]);
    			}
    		}
    	}
    	
    - Output
    	Before Sort =3
    	Before Sort =4
    	Before Sort =1
    	After Sort =1
    	After Sort =3
    	After Sort =4
    	
  • Example of User defined Object sorting using Comparator interface
  • - Employee class
    	public class Employee {
    
    		String name;
    		int employeeId;
    
    		public Employee(String name, int employeeId) {
    			this.name = name;
    			this.employeeId = employeeId;
    		}
    
    		public String toString() {
    			return this.name + " and " + this.employeeId;
    		}
    	}
    	
    - Sort by Employee Id
    	import java.util.Comparator;
    
    	public class SortByEmployeeId implements Comparator< Employee> {
    
    		// Ascending order of employee number
    		public int compare(Employee emp1, Employee emp2) {
    			return emp1.employeeId - emp2.employeeId;
    		}
    	}
    	
    - Run the Example
    	import java.util.ArrayList;
    	import java.util.Collections;
    	import java.util.List;
    
    	public class ComparatorSortExample {
    
    		public static void main(String[] args) {
    			List< Employee> empList = new ArrayList< Employee>();
    			empList.add(new Employee("Sachin", 500));
    			empList.add(new Employee("Rahul", 10));
    			empList.add(new Employee("Gopal", 344));
    			empList.add(new Employee("Yogesh", 800));
    
    			System.out.println("Unsorted by Employee Id-");
    			for (int i = 0; i < empList.size(); i++) {
    				System.out.println("Before Sort =" + empList.get(i));
    			}
    
    			Collections.sort(empList, new SortByEmployeeId());
    
    			System.out.println("Sorted by Employee Id-");
    			for (int i = 0; i < empList.size(); i++) {
    				System.out.println(empList.get(i));
    			}
    		}
    	}
    	
    - Output
    	Unsorted by Employee Id-
    	Before Sort =Sachin and 500
    	Before Sort =Rahul and 10
    	Before Sort =Gopal and 344
    	Before Sort =Yogesh and 800
    	Sorted by Employee Id-
    	Rahul and 10
    	Gopal and 344
    	Sachin and 500
    	Yogesh and 800
    	
  • Example of sorting an ArrayList in Ascending and Descending order using Collections class.
  • - Student class which implements Comparable interface
    	public class Student implements Comparable< Student> {
    		int rollNo;
    		String name;
    
    		Student(int rollNo, String name) {
    			this.rollNo = rollNo;
    			this.name = name;
    		}
    
    		public int compareTo(Student st) {
    			if (rollNo == st.rollNo)
    				return 0;
    			else if (rollNo > st.rollNo)
    				return 1;
    			else
    				return -1;
    		}
    	}
    	
    - Run the Example
    	import java.util.ArrayList;
    	import java.util.Collections;
    	import java.util.List;
    
    	public class ComparableSortExample {
    		public static void main(String args[]) {
    			List< Student> al = new ArrayList< Student>();
    			al.add(new Student(101, "Gopal"));
    			al.add(new Student(106, "Sachin"));
    			al.add(new Student(105, "Yogesh"));
    
    			Collections.sort(al);
    			for (Student st : al) {
    				System.out.println(st.rollNo + " " + st.name);
    			}
    		}
    	}
    	
    -Output
    	101 Gopal
    	105 Yogesh
    	106 Sachin
    	
  • Example of Bubble sorting
  • In bubble sort algorithm, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.
    	public class BubbleSortExample {
    
    		public static void main(String[] args) {
    			int array[] = { 3, 60, 35, 32, 5 };
    
    			System.out.println("Array Before Bubble Sort");
    			for (int i = 0; i < array.length; i++) {
    				System.out.print(array[i] + " ");
    			}
    
    			// sorting array elements using bubble sort
    			int n = array.length;
    			int temp = 0;
    			for (int outer = 0; outer < n; outer++) {
    				for (int inner = 1; inner < (n - outer); inner++) {
    					if (array[inner - 1] > array[inner]) {
    						// swap elements
    						temp = array[inner - 1];
    						array[inner - 1] = array[inner];
    						array[inner] = temp;
    					}
    				}
    			}
    
    			System.out.println("\n Array After Bubble Sort");
    			for (int i = 0; i < array.length; i++) {
    				System.out.print(array[i] + " ");
    			}
    
    		}
    	}
    	
    - Output
    	Array Before Bubble Sort
    	3 60 35 32 5 
    	 Array After Bubble Sort
    	3 5 32 35 60