您的位置:首页 > 其它

Collections.sort 用法 比较器comparator

2014-07-18 16:55 302 查看
import java.util.Comparator;

首先构造一个比较器
public class SortList implements Comparator{//比较器

public int compare(Object o1,Object o2){

NewsValueContainer nvc1 = (NewsValueContainer)o1;
NewsValueContainer nvc2 = (NewsValueContainer)o2;
returnnvc2.getContainerTitle().compareTo(nvc1.getContainerTitle());
//return  nvc1.getContainerTitle().compareTo(nvc2.getContainerTitle()); 则出来的结果的顺序与上面的相反
}
}

import java.util.Comparator;

public class SortNewsValue implements Comparator{//必须要实现Comparator
public int compare(Object o1,Object o2){//重写compare函数就行
NewsValue nv1 = (NewsValue)o1 ;//NewsValue是你要排序的实体类,javabean
NewsValue nv2 = (NewsValue)o2 ;
return nv2.getCreatedAt().compareTo(nv1.getCreatedAt());//getCreatedAt()就是获取排序比较的字段
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortNVandNVC {

public static void  listSortNVandNVC(int tag,List<NewsValueContainer> listnvc){
SortNewsValue snv = new SortNewsValue() ;
SortList sl = new SortList() ;
if(0 == tag){//排getContainerTitle()
Collections.sort(listnvc,sl);//第一个参数就是你的list,第二个参数就是你的比较器的对象
for(NewsValueContainer tmp:listnvc){
}
}else{
for(int index = 0 ;index<listnvc.size();index++){
Collections.sort(listnvc.get(index).getNews(),snv);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: