按照优先级排序List

问题场景

应需求要对前端展现的数据排序,后端传过来的是个list,要求按照类A的某个字段排序,A类的M字段有几个取值,比如“0”“1”“2”“3”“9”,目标是按照 0 > 1 > 2 > 9 > 3的顺序排序list。

解决方案

用java自带的工具类Collections排序list,自定义优先级,按照要求输出

CODE

package list;

import java.util.*;

/**
 * Created on 2017/5/26
 * Author: youxingyang.
 */
public class ListSort {

    private static class Test {
        private String x;

        public Test(String x) {
            this.x = x;
        }

        public String getX() {
            return x;
        }

        public void setX(String x) {
            this.x = x;
        }

    }
    public static void main(String[] args) {
        List<Test> list = new ArrayList<>();
        list.add(new Test("0"));
        list.add(new Test("1"));
        list.add(new Test("2"));
        list.add(new Test("1"));
        list.add(new Test("3"));
        list.add(new Test("9"));
        list.add(new Test("0"));
        list.add(new Test("1000"));

        Collections.sort(list, new Comparator<Test>() {
            @Override
            public int compare(Test t1, Test t2) {
                return sortRisk(Integer.parseInt(t1.getX()), Integer.parseInt(t2.getX()));
            }
        });

        for(Test t : list) {
            System.out.println(t.getX());
        }
    }

    /**
     * 给出排序标准
     * @param i
     * @param j
     * @return
     */
    private static int sortRisk(int i, int j) {
        return getPriority(j) - getPriority(i);
    }

    /**
     * 给出自定义优先级:返回数字越大优先级越高
     * @param i input
     * @return  priority
     */
    private static int getPriority(int i) {
        int a;
        if (i == 0) {
            a = 10;
        } else if (i == 1) {
            a = 9;
        } else if (i == 2) {
            a = 8;
        } else if (i == 9) {
            a = 7;
        } else if (i == 3) {
            a = 6;
        } else {
            a = 5;
        }
        return a;
    }
}


结果

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值