Steve
Steve

Reputation: 406

Get sorted values of Matrix in Java

I'm totally new in Java. I need to "sort" the value of a matrix in Java but I don't know how to do.

This is my matrix:

double matrix = new double[3][3];
// fill matrix with some random values

The result of the matrix could be something like this:

3,4    9.4    7.7
4,1    3.48   9.9
1,6    3.5    5.3

Now I need to get the i & j value of this matrix in decrease order of the corresponding value. There are some way to do that?

In this case the vector with the sorted value it should contain something like this: (1,2), (0,1), (0,2), (2,2) ... (2,1)

Upvotes: 0

Views: 72

Answers (1)

Aso Strife
Aso Strife

Reputation: 1129

With Java 8 you can do this with Lambda:

int rows = matrix.lenght;
int cols = matix[0].lenght;

List<List<Integer>>orderedSavingsList = IntStream.range(0, rows).mapToObj(i ->
            IntStream.range(0, cols).mapToObj(j ->
                    new double[]{i, j, matrix[i][j]}
            )
    )
    .flatMap(x -> x).filter(t -> t[0] < t[1])
    .sorted((a, b) -> Double.compare(b[2], a[2]))
    .map(a -> Arrays.asList((int) a[0], (int) a[1]))
    .collect(Collectors.toList());

After that try to print the list with:

orderedSavingsList.forEach(System.out::println);

Upvotes: 1

Related Questions