Java按照自定義list排序數據

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章