Java Sorting

How to Sort an Array, List, Map or Stream in Java

Learn to sort a Java Set, List and Map of primitive types and custom objects using Comparator, Comparable and new lambda expressions. We will learn to sort in ascending and descending order as well. 1. Sorting a List of Objects To sort a list of objects, we have two popular …

Java Stream – Sort with Null Values

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 …

Sorting a Stream by Multiple Fields in Java

Java 8 example to sort stream of objects by multiple fields using comparators and Comparator.thenComparing() method. This method returns a lexicographic-order comparator with another comparator. It gives the same effect as SQL group by clause.

How to Sort a Stream in Java

Learn to sort stream of numbers and strings in ascending (natural order) and descending orders (reverse order) using Stream.sorted() method.

Java group by sort – multiple comparators example

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 …

Java Collections sort()

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. …

Sorting Arrays in Java

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 …

Sort a Map by Values in Java

Simple and easy-to-understand examples of sorting a HashMap by values, using Java 8 Stream, in ascending and descending (reverse) orders.

Sort a Map by Keys in Java

Simple and easy-to-understand examples to sort a Map by key, using TreeMap and Java 8 Stream, in ascending and descending (reverse) orders.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.