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();  
    }  
});  

 

 

你可能感兴趣的:(object)