Skip to content

Commit 605e484

Browse files
committed
Comparator nullsFirst and nullsLast
1 parent df3fa2d commit 605e484

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Modern-Java-Examples/src/com/learn/defaults/DefaultsMethodsExample2.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ public static void main(String[] args) {
2727

2828
comparatorChain(studentList);
2929

30+
sortWithNullValues(studentList);
3031
}
3132

3233
public static void sortByName(List<Student> studentList) {
@@ -54,4 +55,27 @@ public static void comparatorChain(List<Student> studentList) {
5455
studentList.sort(gradeComparator.thenComparing(nameComparator));
5556
studentList.forEach(studentConsumer);
5657
}
58+
59+
/**
60+
* If our collection value has null value, but we try to perform sort using comparator.
61+
* It will throw NullPointer Exception
62+
* To handle these scenarios, Comparator has handy method nulls First and nulls last.
63+
*/
64+
public static void sortCollectionHavingWithNull() {
65+
System.out.println("List with Null");
66+
List<Student> studentList = StudentDataBase.getAllStudents();
67+
studentList.add(null);
68+
// comparatorChain(studentList); // throw NPE
69+
}
70+
71+
/**
72+
* nullsFirst() : pushes null value at first
73+
* nullsLast() : null values will be pushed towards the end.
74+
*/
75+
public static void sortWithNullValues(List<Student> studentList) {
76+
studentList.add(null);
77+
Comparator<Student> studentComparator = Comparator.nullsFirst(nameComparator);
78+
studentList.sort(studentComparator);
79+
studentList.forEach(studentConsumer); // prints null first.
80+
}
5781
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ This repository contains the basic &amp; advance level examples related to Java
6565
* **Defaults**
6666
* [default methods](Modern-Java-Examples/src/com/learn/defaults/DefaultsMethodExample.java)
6767
* [sort using Comparator](Modern-Java-Examples/src/com/learn/defaults/DefaultsMethodsExample2.java)
68+
* [Comparator: nullsFirst and nullsLast](Modern-Java-Examples/src/com/learn/defaults/DefaultsMethodsExample2.java)
6869

6970
<hr />
7071

0 commit comments

Comments
 (0)