In Java, we can sort collections of data using various sorting algorithms and Java’s built-in sorting capabilities provided by the java.util.Collections class or the Arrays class.
Learn by examples.
Related Tags
Tutorials
To sort a Java Stream or List that contains null values, wrap the comparator in Comparator.nullsFirst() or nullsLast(). Examples for null elements, null fields, descending order and the reversed() trap.
Sort arrays, lists, streams, maps and sets in Java with Arrays.sort(), list.sort(), sorted() and Comparator chains. Also covers descending int[] arrays, null values, Collator, stable sorting and comparator mistakes that give wrong orders.
Learn to sort a Java List or Stream with Comparator‘s nullsFirst() and nullsLast() methods. The Stream may contain null values, or the custom objects may have null field values. Failing to handle the null values during comparison will cause NullPointerException in runtime. 1. Introduction In this tutorial, we will learn …
Java examples to do SQL-style group by sort on list of objects. It involves using multiple comparators, each of which is capable of sorting on different field in model object. Table of Contents 1. Model class and multiple comparators 2. Comparator.thenComparing() 3. CompareToBuilder 4. ComparisonChain 5. Chained comparators 1. Model …
Learn to sort a string alphabetically using Stream.sort(), Arrays.sort() and custom sort() method using simple arrays and swapping example.
Java 8 example of sorting a collection of objects on multiple fields (ORDER BY sort) using Comparator thenComparing() method.
Learn to use Collections.sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections.reverseOrder() method, which returns a Comparator, for reverse sorting. 1. Sorting in Natural Order and Reverse Order 1.1. …
Learn to sort a Java array of primitives, strings and custom objects in multiple ways with the help of Comparable and Comparator interfaces, Arrays.sort() and Stream.sorted() APIs. We will learn to sort arrays in natural ordering, reverse ordering and any other custom ordering as well. 1. Basics of Array Sorting …
Simple and easy-to-understand examples of sorting a HashMap by values, using Java 8 Stream, in ascending and descending (reverse) orders.
Simple and easy-to-understand examples to sort a Map by key, using TreeMap and Java 8 Stream, in ascending and descending (reverse) orders.
Easy to follow examples of sorting a collection of objects in any order using Comparable or Comparator Interfaces.