JAVA: Sort ArrayList<ArrayList<Integer>> on multiple columns

By : Bob
Source: Stackoverflow.com
Question!

First, I did do my homework searching before posting here. My requirement seems to be slightly different compared to questions posted out there.

I have a matrix like ArrayList<ArrayList<Integer>> in the following form

| id1 | id2 | score |
|-----|-----|-------|
| 1   | 3   | 95%   |
| 1   | 2   | 100%  |
| 1   | 4   | 85%   |
| 1   | 5   | 95%   |
| 2   | 10  | 80%   |
| 2   | 15  | 99%   |

I want to sort the matrix column-wise (first using score, then the id1). I already have the id1 in a sorted manner. That means I also need to sort all records with the same id1 first by using score, second by the id2. The reason for doing this is to create a ranking of the id2 in each id1. The result for the above example would be:

| q_id | d_id | rank | score |
|------|------|------|-------|
| 1    | 2    | 1    | 100%  |
| 1    | 3    | 2    | 95%   |
| 1    | 5    | 3    | 95%   |
| 1    | 4    | 4    | 85%   |
| 2    | 15   | 1    | 99%   |
| 2    | 10   | 2    | 80%   |

How can I achieve this in Java using some built-in methods of collections?

By : Bob


Answers

First off, you're better holding your data in a Plain Old Java Object (POJO) rather than a List of Lists of Integers.

From your example, it seems as though your data has three elements: two ids and a score. A POJO might be like this:

public class Record() {
    private int id1;
    private int id2;
    private double score; // percent, so double from 0.0 to 1.0

    public Record(int id1, int id2, double score) {
        this.id1=id1;
        this.id2=id2;
        this.score=score;
    }
    // getters and setters
}

Then instead of your complicated sub-lists, you'd just have a List



Create an Object that includes all columns/fields of your each ArrayList row. Then make use of Comparator interface and use Collections.sort().

You can check out http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)



A proper OO solution would be to declare this as

class Bucket {
    int val1;
    int val2;
    int percent;
}

List


This video can help you solving your question :)
By: admin