How to Sort a List in Java

There are multiple way to Sort a List in java.

From Comparator method :-

Collections class sort() method is used to sort a list in Java. here we create a comparator and pass it as an argument to the Collections.sort() method.A comparator is an object that implements the java.util.Comparator interface. It has a single method called compare() that compares two objects and returns an integer indicating their relative order.

From compareTo method :-

Here Collections.sort method take list and string type data. through lambda expression we call a1.compareTo(a2),compareTo() method that compares two objects and returns an integer indicating their relative order.

From sort Method :-

Inside sort method pass two String type data and use that data from lambda expression, execute p.compareTo(q) that compares two objects and returns an integer indicating their relative order.

				
					import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ListSort {
	
	public static void main(String[] args) {
		List<String> list = Arrays.asList("Mumbai", "Delhi", "Chennai", "Pune");
		
		Collections.sort(list, new Comparator<String>() {
			public int compare(String s1, String s2) {
				return s1.compareTo(s2);
			}
		});
		System.out.println("sort list from Comparator method :- " + list);
		
		Collections.sort(list, (String a1, String a2) -> a1.compareTo(a2));
		System.out.println("sort list from compareTo method :- " + list);
		
		list.sort((p, q) -> p.compareTo(q));
		System.out.println("sort with lambda expression method :- " + list);
	}

}

				
			

Output :-
sort list from Comparator method :- [Chennai, Delhi, Mumbai, Pune]
sort list from compareTo method :- [Chennai, Delhi, Mumbai, Pune]
sort with lambda expression method :- [Chennai, Delhi, Mumbai, Pune]