Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort Arrays in a Collection?

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):

  • compare the first int of each array
  • if they are equal, compare the next int of each array (and so on)
  • if they aren't equal the result of the comparison is the end result.

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.

like image 720
Maikefer Avatar asked Mar 24 '16 19:03

Maikefer


People also ask

Can you do Collections sort array?

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.

How do you sort an array in descending order using collection methods?

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.

Which sorting is used in Collections sort?

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.


1 Answers

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).

like image 140
Paul Boddington Avatar answered Sep 18 '22 08:09

Paul Boddington