0

I am writing some java code for my project and I came across this issue that I do not know how to deal with. I have a two-dimensional array like this:

Object[][] array = new Object[10][3]; 

Which has inner types: [String, String, Double]

Example:

[[apple, car, 10.7], [melon, train, 3.4], [peach, plane, 5.2]]

I need to sort it by the last double, in the ascending order without creating my own sort function.

Desired result:

[[melon, train, 3.4], [peach, plane, 5.2], [apple, car, 10.7]]

Can someone please help me?

PS (I tried all of the solutions from the post that is tagged here as "this question was answered before" and none of those worked for me. The first reply here, however, solved my issue. Thank you!)

1
  • 1
    Arrays.sort(array, Comparator.comparingDouble(a -> (double) a[2])); Commented Feb 19, 2019 at 4:34

1 Answer 1

0

Try this:

Object[][] array = new Object[10][3];
// fill the array

Object[][] sortedArray = Arrays.stream(array)
        .filter(v -> v[2] != null) //not required if you have the array completely filled
        .sorted(Comparator.comparingDouble(v -> (double) v[2]))
        .toArray(Object[][]::new);

System.out.println(Arrays.deepToString(sortedArray));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.