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: Group by multiple fields – Example Example of using thenComparing() to create Comparator which is capable of sorting by multiple fields. […]
Learn to use Collections.sort() method to sort collections in java with examples. By default, this method sorts the unsorted list into ascending order, according to the natural ordering of its elements. 1) Collections.sort( list ) It sorts the specified list into ascending order or their natural order. All elements in the list must implement the […]
Java examples to sort list of objects or primitives (e.g. int, long) using List.sort(), Collections.sort() and sorting with Java stream API. Examples of sorting in natural and reverse order as well. 1) Sort list of objects Examples to sort an arraylist of objects using different sorting techniques. 2) Sort list of primitives Examples to sort […]
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.