Java按照自定义list排序数据

末鹿安然 提交于 2020-01-20 07:35:44

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!