0

I am making use of the following ArrayList: ArrayList<float[]> notes = new ArrayList<float[]>();

I managed to perform the sorting on the first element of the float[] array without any problem. Now I am also trying to sort the ArrayList on using a second attributes. However I cannot manage to sort the list again on the second element of the float arrays ie. float[1].

Any hints?

peterS
  • 71
  • 1
  • 2
  • 6

1 Answers1

0

You can use Collections.sort to sort the array and then use your own Comparator to specify how you want to sort the values.

ArrayList<float[]> notes = new ArrayList<float[]>();
//adding some dummy data to the list
notes.add(new float[]{5f,6f,1f});
notes.add(new float[]{5f,2f,1f});
notes.add(new float[]{5f,1f,1f});

//Use Collections.sort to sort Ascending values on the second value in the float arrays
Collections.sort(notes, new Comparator<float[]>() {
    @Override
    public int compare(float[] o1, float[] o2) {
        if (o1[1] > o2[1]){
            return 1;
        }else if(o1[1] < o2[1]){
            return -1;
        }
        return 0;
    }
});

//Output the values
for (float[] f : notes){
    System.out.println(Arrays.toString(f));
}

Output:

[5.0, 1.0, 1.0]
[5.0, 2.0, 1.0]
[5.0, 6.0, 1.0]
Sean F
  • 2,352
  • 3
  • 28
  • 40
  • Hint for simpler comparison: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#compare%28float,%20float%29 – JB Nizet Apr 08 '15 at 07:46