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 class and multiple comparators Our […]
Java example to sort characters of String in alphabetical order – using Stream.sorted() and Arrays.sort() methods. 1) Sort string with Stream API Example of sorting the characters of string using Stream.sorted() API. 2) Arrays.sort() Example of sort a string using Arrays.sort() method. Drop me your questions in comments section. Happy Learning !! Reference: Stream.sorted() Java […]
Java example to sort list of objects by multiple fields using Comparator.thenComparing() method. This method returns a lexicographic-order comparator with another comparator. It gives the same effect as SQL group by clause. Quick Reference: Sort on multiple fields – Group by sort Example of using thenComparing() to create Comparator which is capable of sorting by […]
Learn to use Collections.sort() method to sort arraylist of custom objects in java with examples. By default, this method sorts the unsorted list into ascending order, according to the natural ordering of its elements. We can use Collections.reverseOrder() method for reverse sorting. 1. Sort ArrayList of objects – Collections.sort( list ) It sorts the specified […]
Java program to sort arraylist of strings and integers using different sorting techniques in natural order (alphabetically) and reverse order.
Java example to sort an array of primitives and objects which implement Comparable interface. Quick Reference: 1) Sort array of primitives Use Arrays.sort() method to sort an array of primitives such as int, long or String values. 1.1) Sort array in reverse order Use Arrays.sort(arr,Collections.reverseOrder()) to sort an array in reverse oder. 2) Sort array […]
Simple quick to use examples to sort Map by values, using Java 8 Stream APIs, in ascending and descending (reverse) orders. In the center of logic is the method Map.Entry.comparingByValue() which compares Map.Entry in natural order on value. Sort Map by Values using Stream APIs In java 8, Map.Entry class has static method comparingByValue() to […]
Simple quick to use examples to sort a Map by key, using TreeMap and Stream APIs, in ascending and descending (reverse) orders.
Easy to follow examples of sorting a collection of objects in any order using Comparable or Comparator Interfaces.