使用java中的集合排序

swa*_*ati 0 java sorting collections

我在使用集合进行排序时遇到了一个棘手的问题.

我有一个HashMap,其中包含以下内容

HashMap<String,QuoteBean> mapToSort=new HashMap<<String,QuoteBean>();
Run Code Online (Sandbox Code Playgroud)

QuoteBean基本上是一个java bean,它具有setter和getter方法的属性,如下所示.

//class QuoteBean defination

Class QuoteBean implements Serializable{
  private BigDecimal currentPricel
  private BigDecimal  change;
  private BigDecimal TotalChange;
  private String symbol;

//with getter and setter methods  

}//end of the class
Run Code Online (Sandbox Code Playgroud)

现在,当我从地图中获取值时,我通常会得到这样的结果

Collection values=mapToSort.values();//which will return all the values in the map
Run Code Online (Sandbox Code Playgroud)

This values is basically a collection of QuoteBean objects. I want to sort the beans before sending it to the client. Now i can use the comparator interface and sort it .. But the problem is the sorting criteria changes frequently . I mean some time the client wants to sort with symbol,some times the client wants with change some times with total gain. The criteria changes very often. Is there a way to write the " compare " function to overload and which will satisfy all the conditions...

Is there any good way of solving this problem..

I would really appreciate if some one can reply to this topic

Thanks,

Boz*_*zho 6

是.实现java.util.Comparator接口并使用重载方法:(例如Collections.sort(list, comparator),您需要List从集合的元素创建一个新的new ArrayList(collection))

所以你可以:

public CurrentPriceQuoteComparator implements Comparator<QuoteBean> {
    @Override
    public int compare(QuoteBean b1, QuoteBean b2) { // implement comparison }
}

public ChangeQuoteComparator implements Comparator<QuoteBean> {
    @Override
    public int compare(QuoteBean b1, QuoteBean b2) { // implement comparison }
}
Run Code Online (Sandbox Code Playgroud)

然后使用 Collections.sort(list, ChangeQuoteComparator.INSTANCE);

请注意,最好是声明每个比较器的单例实例,而不是每次都实例化它:

public static final ChangeQuoteComparator INSTANCE = 
     new ChangeQuoteComparator();
Run Code Online (Sandbox Code Playgroud)

要进一步扩展,可以enum使用不同的比较类型定义:

public enum ComparisonType {
   CHANGE, CURRENT_PRICE; // etc..
}
Run Code Online (Sandbox Code Playgroud)

并定义一个Map匹配每个比较类型与适当的比较器:

private static final Map<ComparisonType, Comparator<QuoteBean>> comparators = 
      new HashMapMap<ComparisonType, Comparator<QuoteBean>>();

static {
   comparators.put(ComparisonType.CHANGE, ChangeQuoteComparator.INSTANCE);
   comparators.put(ComparisonType.CURENT_PRICE, 
           CurrentPriceQuoteComparator.INSTANCE);
}
Run Code Online (Sandbox Code Playgroud)

然后让客户指定他想要的比较

 public List<QuoteBean> getOrdered(ComparisonType type, // other criteria) {
     List<QuoteBean> list = new ArrayList<QuoteBean>(getQuotesCollection());
     Collections.sort(list, comparators.get(type));
     return list;
 }
Run Code Online (Sandbox Code Playgroud)