java 根据对象的boolean字段对集合进行排序
需求大概如下: 把boolean为true的排序到前面,false排序到后面
排序后, boolean为true的会在前面, 为false的会在后面 ,
isHasMaterial 为boolean类型
@Data
@Builder
public class MoguPoiBaseInfo {/*** 是否有素材,默认false代表没素材,为true代表有素材*/private boolean hasMaterial = false;
}
public void sortByMoguPoiBaseInfo(List<MoguPoiBaseInfo> doSortList) {if (CollectionUtils.isEmpty(doSortList)) {return;}//重写Comparator()方法doSortList.sort((o1, o2) -> {//得到要比较的两个对象的某个字段,这里是requiredboolean o1HasMaterial = o1.isHasMaterial();boolean o2HasMaterial = o2.isHasMaterial();//两个值进行位运算,值不同为1,为true,参与运算//值相同为0,为false,不参与运算if (o1HasMaterial ^ o2HasMaterial) {return o1HasMaterial ? -1 : 1;} else {return 0;}});}
单测
@Testpublic void sortByMoguPoiBaseInfo() {List<MoguPoiBaseInfo> doSortList = new ArrayList<>();MoguVideoSyntheticActionImpl moguVideoSyntheticAction = new MoguVideoSyntheticActionImpl();moguVideoSyntheticAction.sortByMoguPoiBaseInfo(doSortList);System.out.println("JSON.toJSONString(doSortList) = " + JSON.toJSONString(doSortList));moguVideoSyntheticAction.sortByMoguPoiBaseInfo(null);System.out.println("JSON.toJSONString(doSortList) 2222= ");;doSortList.add(MoguPoiBaseInfo.builder().hasMaterial(false).poiId(1L).build());doSortList.add(MoguPoiBaseInfo.builder().hasMaterial(true).poiId(2L).build());doSortList.add(MoguPoiBaseInfo.builder().hasMaterial(false).poiId(3L).build());moguVideoSyntheticAction.sortByMoguPoiBaseInfo(doSortList);System.out.println("JSON.toJSONString(doSortList) = " + JSON.toJSONString(doSortList));}