Sorting In Java 8

Sanjay Singh
1 min readApr 25, 2022

--

Java 8 — How to Sort List with Stream.sorted()
====================
List<Integer> list = Arrays.asList(10, 23, -4, 0, 18);
List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());
System.out.println(list);
System.out.println(sortedList);
========
Sorting a List of Integers in Descending Order with Stream.sorted()

List<Integer> list = Arrays.asList(10, 23, -4, 0, 18);
List<Integer> sortedList = list.stream()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());

System.out.println(sortedList);
================
Sorting Custom Objects with Stream.sorted(Comparator<? super T> comparator)
List<User> sortedList = userList.stream()
.sorted(Comparator.comparingInt(User::getAge).reversed())
.collect(Collectors.toList());

sortedList.forEach(System.out::println);

============
List<User> userList = new ArrayList<>(Arrays.asList(
new User(“John”, 33),
new User(“Robert”, 26),
new User(“Mark”, 26),
new User(“Brandon”, 42)));

List<User> sortedList = userList.stream()
.sorted((o1, o2) -> {
if(o1.getAge() == o2.getAge())
return o1.getName().compareTo(o2.getName());
else if(o1.getAge() > o2.getAge())
return 1;
else return -1;
})
.collect(Collectors.toList());

sortedList.forEach(System.out::println);

=============

Comparator<User> customComparator = new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
if(o1.getAge() == o2.getAge())
return o1.getName().compareTo(o2.getName());
else if(o1.getAge() > o2.getAge())
return 1;
else return -1;
}
};

List<User> sortedList = userList.stream()
.sorted(customComparator)
.collect(Collectors.toList());

==============================

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet