We have to sort a given linked list according to default alphabetical order or customized sorting order.
Example – Program to sort a linked list according to default alphabetical order
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class SortLinkedList { public static void main(String args[]) { List<String> list = new LinkedList<String>(); list.add("Apple"); list.add("carrot"); list.add("oats"); list.add("beans"); System.out.println("before sorting: " + list); Collections.sort(list); System.out.println("after sorting: " + list); } }
Output
before sorting: [Apple, carrot, oats, beans] after sorting: [Apple, beans, carrot, oats]
Example – Reverse alphabetical order sorting using Comparator Interface
import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class SortLinkedList { public static void main(String args[]) { List<String> list = new LinkedList<String>(); list.add("Apple"); list.add("carrot"); list.add("oats"); list.add("beans"); System.out.println("before sorting: " + list); Collections.sort(list, new MyComparator()); System.out.println("after sorting: " + list); } } class MyComparator implements Comparator { @Override public int compare(Object t1, Object t2) { String a1 = t1.toString(); String a2 = t2.toString(); return a2.compareTo(a1);// return reverse of alphabetical order } }
Output
before sorting: [Apple, carrot, oats, beans] after sorting: [oats, carrot, beans, Apple]