2013-08-20 88 views
1

的數組列表我有一個數據結構,如下所示:排序中包含HashMap

public class VResultSetBean { 
    private ArrayList<RowBean> rowBeans; 
} 

public class RowBean { 
    private HashMap<String, Object> columns; 
} 

我需要基於在HashMap中columns的關鍵之一的值進行排序rowBeans。用Java做這件事最有效的方法是什麼?

回答

6

使RowBean執行Comparable並執行compareTo方法來拉出該鍵的值,並用它來決定比較結果。

public class RowBean implements Comparable<RowBean> { 

    private HashMap<String, Object> columns; 

    @Override 
    public int compareTo(RowBean other) { 
      Object valOther = other.columns.get(...); 
      Object valMine = columns.get(...); 
      return comparison(valOther, valMine); 
    } 
} 

一旦RowBean是一個Comparable您可以排序使用:

Collections.sort(rowBeans); 
0

首先,有沒有辦法比較Object類的兩個對象,他們需要有一種方式來獲得比:這是實施界面Comparable。所以你需要將columns更改爲HashMap<String, Comparable>

之後,你可以一個比較方法添加到RowBean這樣的:

class RowBean { 

    private HashMap<String, Comparable> columns; 

    public int compare(String column, RowBean other) { 
     return columns.get(column).compareTo(other.columns.get(column)); 
    } 

} 

最後,排序列表,你可以使用一個化名Comparator,這種方式:

List<RowBean> list = new ArrayList<>(); 

final String sortingColumn = "myColumn"; 

Collections.sort(list, new Comparator<RowBean>() { 
    @Override 
    public int compare(RowBean o1, RowBean o2) { 
     return o1.compare(sortingColumn, o2); 
    } 
}); 
1

這是爲我工作的最終代碼片段。謝謝你們..

public class RowBean implements Comparable<RowBean> { 
     HashMap<String, Object> columns; 
     public int compareTo(RowBean other) { 
      Object valOther = other.columns.get("CONVERSIONS"); 
      Object valMine = columns.get("CONVERSIONS"); 
      return comparison(valOther, valMine); 
     } 
     private int comparison(Object valOther, Object valMine) { 
      if((Long) valMine > (Long)valOther) 
       return 1; 
      else if((Long) valMine < (Long)valOther) 
       return -1; 
      else 
       return 0; 
     } 
    }