![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to sort a list placing nulls in the end
Let us create a list first with string elements. Some of the elements are null in the List:
List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk");
Now, sort the above list and place nulls in the end with nullsLast:
list.sort(Comparator.nullsLast(String::compareTo));
The following is an example to sort a list placing nulls in the end:
Example
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String... args) { List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk"); System.out.println("Initial List = "+list); list.sort(Comparator.nullsLast(String::compareTo)); System.out.println("List placing nulls in the end = "+list); } }
Output
Initial List = [Jack, null, Thor, null, Loki, Peter, null, Hulk] List placing nulls in the end = [Hulk, Jack, Loki, Peter, Thor, null, null, null]
Advertisements