ComparisonChain 使用
有一个产品的list,想对这个list先按产品生效时间排序,如果生效时间一样再按失效时间排序,代码如下:
package collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import com.google.common.collect.ComparisonChain;
public class TestListSort {
public static void main(String[] args) {
List<Product> list = new ArrayList<Product>();
Product prod1 = new Product(new Date(2015, 4, 21), new Date(2015, 4, 22),
1);
list.add(prod1);
Product prod2 = new Product(new Date(2015, 4, 21), new Date(2015, 4, 21),
2);
list.add(prod2);
Product prod3 = new Product(new Date(2015, 4, 20), new Date(2015, 4, 21),
3);
list.add(prod3);
printList(list);
sort(list);
printList(list);
}
public static void sort(List<Product> list){
Collections.sort(list,new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
return ComparisonChain.start().compare(p1.getValid(), p2.getValid()).
compare(p1.getExpire(), p2.getExpire()).result();
}
});
}
public static void printList(List