欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java List根据多个参数排序

程序员文章站 2024-03-17 09:36:16
...
依赖(commons-collections-3.2.1.jar和commons-beanutils-1.8.2.jar):
import java.util.Collections;
import java.util.Comparator;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;

代码:
Comparator myCom1 = ComparableComparator.getInstance();
Comparator myCom2 = ComparableComparator.getInstance ();
myCom1= ComparatorUtils. nullHighComparator(myCom1); //允许null
myCom2 = ComparatorUtils. nullHighComparator(myCom2); //允许null
//默认为正序,可选择设置为逆序
//myCom1 = ComparatorUtils.reversedComparator(myCom1);
//myCom2 = ComparatorUtils.reversedComparator(myCom2);
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add( new BeanComparator("age" , myCom1)); //第一排序
sortFields.add( new BeanComparator("classes" , myCom2)); //第二排序
//创建一个排序链
ComparatorChain multiSort = new ComparatorChain(sortFields);
Collections.sort(list, multiSort);

 

相关标签: 个人成长