`
sunxboy
  • 浏览: 2878048 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Ways to sort lists of objects in Java based on multiple fields

 
阅读更多

1. the first way:

Sorting with Google Guava’s ComparisonChain

Collections.sort(pizzas, new Comparator<Pizza>() {  
    @Override  
    public int compare(Pizza p1, Pizza p2) {  
        return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();  
        // or in case the fields can be null:  
        /* 
          return ComparisonChain.start() 
              .compare(p1.size, p2.size, Ordering.natural().nullsLast()) 
              .compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast()) 
              .compare(p1.name, p2.name, Ordering.natural().nullsLast()) 
              .result(); 
         */  
    }  
}); 

 

 

 

2. the second way:

Sorting with Apache Commons CompareToBuilder

Collections.sort(pizzas, new Comparator<Pizza>() {  
    @Override  
    public int compare(Pizza p1, Pizza p2) {  
        return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();  
    }  
});  

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics