2012-09-17 63 views
0

首先,我在發佈之前做過功課搜索。與我發佈的問題相比,我的要求似乎略有不同。JAVA:在多列上對ArrayList <ArrayList <Integer>>排序

我有一個像ArrayList<ArrayList<Integer>>矩陣在下文形式

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

欲逐列(第一使用得分,則ID1)的矩陣進行排序。我已經有一個排序方式的id1。這意味着我還需要使用分數排序所有具有相同id1的記錄,其次是id2。這樣做的原因是在每個id1中創建i​​d2的排名。上述示例的結果是:

| 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% | 

如何在Java中使用一些內置的集合方法實現此目的?

+0

爲什麼不使用從[番石榴類別]的'Table'類型(http://code.google.com/p/guava-libraries/)? –

+0

你能否詳細說明你想實現的目標? – PermGenError

+0

你想要一個變化的桶排序/基數排序。第一桶是id1,第二桶是id2。 –

回答

1

創建一個包含每個ArrayList行的所有列/字段的對象。然後使用Comparator接口並使用Collections.sort()。

您可以檢查出http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29

+0

你能更詳細地闡述一下嗎? – Bob

+0

我可以使用一列進行排序。每當我使用第二列進行排序時,是不是會混淆第一個排序性質?或者它足夠聰明,可以讓第一個排序結果以其形式排序,然後使用第二個鍵進行相應排序? – Bob

+0

吉姆回答了我想說的話:) –

1

一個適當的面向對象的解決辦法是把這個聲明爲

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

List<Bucket> myList = ... 

,並提供一個Comparator是排序元素你想要的方式

0

首先,你」最好將數據保存在Plain Old Java Object(POJO)而不是整數列表列表中。

從你的例子看來,你的數據看起來好像有三個元素:兩個ID和一個分數。一個POJO可能是這樣的:

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 
} 

,而不是你複雜的子列表之後,你只是有一個List<Record>

從我對你的問題的理解中,你想先按id1排序,然後按id2排序。是對的嗎?這看起來像它要求radix sort(鏈接到維基百科)。

的僞代碼將是這樣的:

  1. 循環每一個記錄,並通過id1它們歸類到「桶」。每個「桶」可以是List<Record>,並且應該包含具有相同id1的所有Record對象,沒有特定順序。
  2. 循環遍歷每個桶並按id2排序。
  3. 將你所有的桶重新組合在一起,保持秩序。

你會想,以高效,簡潔地實現這個更新與像public int compareId1(Record other)public int compareId2(Record other)方法Record對象。

1

我不確定你所描述的實際上是一個矩陣。它看起來像一羣三胞胎。

考慮爲您的矩陣的每個「行」創建一個包裝類:

class Triplet implements Comparable<Triplet> { 
    private int id1; 
    private int id2; 
    private int score; 

    // getters/setters here 

    @Override 
    int compareTo(Triplet that) { 
     // if I understood correctly, you want to sort by score, then id1, then id2. 
     int result = this.score - that.getScore(); 
     if (result == 0) { 
      result = this.id1 - that.getId1(); 
      if (result == 0) { 
       result = this.id2 - that.getId2(); 
      } 
     } 

     return result; 
    } 
} 

那麼代表你的「矩陣」作爲ArrayList<Triplet>和公正的排序,你通常會。

相關問題