Contents
How do you sort by two fields?
Sorting records in a table by multiple fields
- Right-click a field name and click Advanced Sorting.
- Click the Sort by arrow and click the first field by which you want to sort.
- Click Ascending or Descending to choose the sort order.
- Click the Then sort by arrow, click the next field, then choose a sort order.
Can we use comparable for custom sorting?
Both Comparable and Comparator can be used for custom sorting but there are some differences in their usage. Comparable interface can be used to provide one way of sorting whereas Comparator interface can be used to provide multiple ways of sorting.
How to sort custom objects using comparable interface?
Before we see how to sort an objects of custom objects, lets see how we can sort elements of arrays and Wrapper classes that already implements Comparable. In the above example, you have seen that how easy it is to sort the Arrays and list of objects that implements Comparable interface, you just need to call the Collections.sort (and Arrays.sort).
How to use Comparable interface in Java class?
In the above example, you have seen that how easy it is to sort the Arrays and list of objects that implements Comparable interface, you just need to call the Collections.sort (and Arrays.sort). However if you want to sort the objects of custom class then you need to implement the Comparable interface in our custom class.
How to sort a list of objects using comparable in Java?
We can easily sort the employee’s list first by age and then by name, as shown below. Now for employees having the same age, the ordering is decided by the employee’s name. Note that we have simply reduced the value of int primitive type age from each other while for the String object, built-in comparison method compareTo () is used.
How to sort list of objects on the basis of single field?
In previous articles, we have discussed how to sort list of objects on the basis of single field using Comparable and Comparator interface Read below articles for sorting ArrayList contents in both ascending and descending order on the basis of single field (i.e.; member variable)