Member-only story

Sort List in Java using JAVA 8 different ways.

Gain Java Knowledge
2 min readJul 16, 2023

--

During a project development , every developer comes across a situation where implementation of sorting becomes mandatory. In this article we will mainly focus on sorting using java 8.

Example 1 : Sort a list of String alphabetically.

List<String> names = Arrays.asList("Vivek", "nasim", "Sumit", "gaurav", "Mohit");

Print names in sorting order , now here we will use Comparator to sort a list.

names.sort(Comparator.naturalOrder());

OUTPUT : sorting with natural order : [Mohit, Sumit, Vivek, gaurav, nasim]

naturalOrder() method first place all capital letter names after that small case letter names. So, we can use CASE_INSENSITIVE_ORDER, which return a case insensitive order.

names.sort(String.CASE_INSENSITIVE_ORDER);

OUTPUT : sorting with case Insenesitive : [gaurav, Mohit, nasim, Sumit, Vivek]

Sort A List of Integer :

List<Integer> numbers = Arrays.asList(10, 8, 5, 2, 13, 2);
numbers.sort(Comparator.naturalOrder());

Sorting With Lambda Expression :

List<Employee> employees = Arrays.asList(
new Employee("Sumit", 18, 2000),
new Employee("Karan", 23, 6000),
new Employee("Arjun", 25, 4000)
);

employees.sort((Employee e1, Employee e2) ->
e1.getName().compareTo(e2.getName()));

OUTPUT

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet