I have a a List of Objects. Those Objects have (amongst others) a private int Array (if it helps, I can transfer it into a List). There is a public Getter for this Array. All Arrays are the same size.
I want to sort the Object based on their Arrays like this:
Unsorted:
{[0, 1, 4, 5],
[0, 0, 2, 3],
[0, 1, 1, 2]}
Sorted:
{[0, 0, 2, 3],
[0, 1, 1, 2],
[0, 1, 4, 5]}
In Words (it's called lexicographical):
I manage to search them for e.g. only the first element of the array with a normal Comparator but I don't know how to search them for all.
sort() vs Collections. sort() works for objects Collections like ArrayList, LinkedList, etc. We can use Collections. sort() to sort an array after creating an ArrayList of given array items.
To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
A nice Java 8 solution is
static final Comparator<CustomObject> COMPARATOR = (o1, o2) -> {
int[] arr1 = o1.getArray();
int[] arr2 = o2.getArray();
return IntStream.range(0, arr1.length)
.map(i -> Integer.compare(arr1[i], arr2[i]))
.filter(i -> i != 0)
.findFirst()
.orElse(0);
};
Then, given a List<CustomObject>
, you can do
list.sort(COMPARATOR);
(The Comparator
only works for arrays of the same length. You may want to modify it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With