1、List多个字段排序
List集合排序是通过java.util.Collections中的sort方法实现的,我们现在的业务场景是:根据List集合中实体bean里面的多个属性字段排序
首先写一个sort方法的比较器MyComparator
public class MyComparator implements Comparator<Object> {然后调用排序
@Override
public int compare(Object o1, Object o2) {
CompanyData com1 = (CompanyData) o1;
CompanyData com2 = (CompanyData) o2;
if (com1.getMemlevel().compareTo(com2.getMemlevel()) != 0){ //如果会员等级不一样
return com1.getMemlevel().compareTo(com2.getMemlevel());
} else if (com1.getCreditLevel().compareTo(com2.getCreditLevel())!=0) {//如果信用等级不一样
return com1.getCreditLevel().compareTo(com2.getCreditLevel());
} else {//按积分
return com1.getIntegral().compareTo(com2.getIntegral());
}
}
}
//按会员等级、信用等级、积分排序
Collections.sort( list, new MyComparator());
2、list集合去重
//去掉重复
public List<CompanyData> removeRepeat(List<CompanyData> all,List<CompanyData> sub){
if (all.size()==0 && sub.size()!=0) {
return sub;
}
for (CompanyData companyData : sub) {
all.add(companyData);
}
Set<Integer> set = new HashSet<Integer>();
List<CompanyData> newList = new ArrayList<CompanyData>();
for (Iterator<CompanyData> iter = all.iterator(); iter.hasNext();) {
CompanyData element = (CompanyData) iter.next();
if (set.add(element.getBelong()))
newList.add(element);
}
return newList;
}
因为set集合只能添加不重复的元素,根据这个特点可以排除掉list集合中的重复元素