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"}]
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值