Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rmg007/a2a255c766ff98ef852aaf78cb0ef01d to your computer and use it in GitHub Desktop.

Select an option

Save rmg007/a2a255c766ff98ef852aaf78cb0ef01d to your computer and use it in GitHub Desktop.
Sort String List Using Comparator Natural Order
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class SortStringListUsingComparatorNaturalOrder {
public static void main(String[] args) {
/*
In this line of code there are four strings first one is starting with B
and last one is starting with a,
means there is two types of strings here: upper case and lower-case strings.
The natural sorting in java is based on ASCII, and ASCII is case-sensitive.
*/
List<String> list = new ArrayList<>(List.of("Byyyyyyyyyyyy", "Dww", "Cxxxxxx", "az"));
list.sort(Comparator.naturalOrder());
//after applying method of natural order method output, we get this:
// Before sorting : [ "Byyyyyyyyyyyy", "Dww", "Cxxxxxx","az" ]
//After sorting : [ "Byyyyyyyyyyyy", "Cxxxxxx","Dww", "az" ]
System.out.println(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment