自定義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"}]