Java – sorting objects in array alphabetically and numerically [closed]

I got an array of objects that have a name and a number. I want to sort them first by the number (from high to low). If two or more objects have the same number, these have to be sorted alphabetically. How can I do this in Java? (The objects have getters for both name and number)

Example Input:

Object1 - AAA - 5
Object2 - ABC - 5
Object3 - XAC - 6
Object4 - ZZZ - 3

Output

Object3 - XAC - 6
Object1 - AAA - 5
Object2 - ABC - 5
Object4 - ZZZ - 3

Answer

You make a custom comparator. Given:

class Item {
   String id;
   int nr;

   // with associated getters and the like.
}

spruce it up to be a full class, using records or Lombok’s @Value.

Then:

Comparator<Item> comparator =
  Comparator
  .comparingInt(Item::getNr).reversed()
  .thenComparing(Item::getId);

Armed with this comparator, you can just invoke sort. If you have an array:

Item[] items = ...;
Arrays.sort(items, comparator);

If you have a list:

List<Item> list = ...;
list.sort(comparator);

NB: I suggest you use List, arrays are a bit annoying and low level.

Leave a Reply

Your email address will not be published. Required fields are marked *