自定义list排序数据:
public class SortTest {
public static void main(String[] args) {
List<String> sortList = Arrays.asList("诸葛亮","鲁班","貂蝉","吕布","安其拉","赵云");
List<People> people = new ArrayList<>();
people.add(new People("鲁班","1"));
people.add(new People("安其拉","1"));
people.add(new People("诸葛亮","1"));
people.add(new People("貂蝉","1"));
people.add(new People("赵云","1"));
List<People> peopleList = people.stream().sorted(
Comparator.comparing(People::getName, (x,y)-> sort(sortList,x,y))
).collect(Collectors.toList());
System.out.println(JSON.toJSON(peopleList));
}
private static int sort(List<String> sortList, String x, String y){
if (x == null && y != null){
return 1;
} else if (x != null && y == null){
return -1;
} else {
for (String sort : sortList) {
if (sort.equals(x)){
return -1;
}
if (sort.equals(y)){
return 0;
}
}
}
return 0;
}
}
运行结果:
[{"name":"诸葛亮","sex":"1"},{"name":"鲁班","sex":"1"},{"name":"貂蝉","sex":"1"},{"name":"安其拉","sex":"1"},{"name":"赵云","sex":"1"}]