0

I'm building a multidimensional array of Objects, and I would want to sort it by a specific element inside the sub-arrays.

I tried Collections.sort and a bubbleSort but they didn't work.

Object[][] fields = {{
      "sam", "mccarty",
      "m", "1988/06/01", 5.0, true
   },
   {
      "tom", "huges",
      "m", "1988/06/01", 7.0, true
   },
   {
      "jim", "ross",
      "m", "1988/06/01", 6.5, true
   }
};

I expect the array sorted by sub-element [4], so:

 {
   {
      "tom", "huges",
      "m", "1988/06/01", 7.0, true
   },
   {
      "jim", "ross",
      "m", "1988/06/01", 6.0, true
   },
   {
      "sam", "mccartney",
      "m", "1988/06/01", 5.5, true
   }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
saga
  • 93
  • 1
  • 7

2 Answers2

0

If all your fields follow the same schema, it could be worth it to wrap them around inside some object, say Person, so that you have a one-dimensional array, and then sort said array using a custom comparator.

You could do something like this:

Person[] fields = {
    new Person("sam", "mccarty", "m", "1988/06/01", 5.0, true),
    ...
};
// Assuming you want things to be sorted in descending order like in your example.
Collections.sort((o1, o2) -> o2.getFourth() - o1.getFourth());

You can find more info on comparators in the docs here.

yaken
  • 559
  • 4
  • 17
0

You can use :

Arrays.sort(fields, (o1, o2) -> Double.compare((Double) o1[4], (Double) o2[4]));

Outputs of double values after sort is :

5.0
6.5
7.0

Better Solution

but I would create an Object, put the necessary field like so :

class MyObject{
    private String fname;
    private String lname;
    private String gender;
    private LocalDate birthDay;
    private Double note;
    private boolean check;
   // @Getter @Setter @Constructors
}

then the sort can be easy :

MyObject[] array = {...};
Arrays.sort(array, Comparator.comparing(MyObject::getNote));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140