需求背景
最近在对一个集合列表的数据进行排序,需求是要集合数据按照一个排序状态值进行排序,而这个状态值,不是按照从小到大这样的顺序排序的,而是要按照特定的顺序,比如按照1, 0, 2
的顺序排的,所以需要自定义一个排序工具类来实现
解决方案
写一个排序工具类
package cn.nzp.ems.ecb.server.business.screen;import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;public class CustomizeNumComparator implements Comparator<Integer>, Serializable {private static final long serialVersionUID = 6076418974912880405L;List<Integer> numList = Stream.of(1, 0, 2).collect(Collectors.toList());@Overridepublic int compare(Integer o1, Integer o2) {int i1 = numList.indexOf(o1);int i2 = numList.indexOf(o2);return (i1 == -1 || i2 == -1) ? (i2 - i1) : i1 - i2;}
}
测试一下排序
@Test
public void testCompare() {List<RecordDto> list = Lists.newArrayList();RecordDto record01= new RecordDto();record01.setOrderNum(2);record01.setSName("测试名称1");RecordDto record02= new RecordDto();record02.setOrderNum(0);record02.setSName("测试名称2");RecordDto record03 = new RecordDto();record03.setOrderNum(1);record03.setSName("测试名称3");RecordDto record04= new RecordDto();record04.setOrderNum(2);record04.setSName("测试名称4");RecordDto record05= new RecordDto ();record05.setOrderNum(0);record05.setSName("测试名称5");list.add(record01);list.add(record02);list.add(record03);list.add(record04);list.add(record05);list = list.stream().sorted(Comparator.comparing(RecordDto::getOrderNum, new CustomizeNumComparator())).collect(Collectors.toList());list.stream().forEach(e -> {System.out.println(e.getName() +", " +e.getOrderNum());});
}
跑一下测试结果
如果不想写一个排序工具类,也可以创建一个Comparator
即可
public void testCompare() {List<Integer> numList = Stream.of(1, 0, 2).collect(Collectors.toList());Comparator<RecordDto> comparingIndex = Comparator.comparing(record -> {final int index = numList.indexOf(record.getOrderNum());return index == -1 ? Long.MAX_VALUE : index;});list = list.stream().sorted(comparingIndex.thenComparing(RecordDto::getCreateTime, Comparator.nullsLast(Date::compareTo))).collect(Collectors.toList());
}