Java 使用 Collections.sort() 排序

只是记录下笔记

RechargeHistoryList.class

public class RechargeHistoryList {
    private int id;
    private int carId;
    private int rechargeVal;//充值金额
    private String rechargeDate;

    public RechargeHistoryList(int carId, int rechargeVal, String rechargeDate) {
        this.carId = carId;
        this.rechargeVal = rechargeVal;
        this.rechargeDate = rechargeDate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCarId() {
        return carId;
    }

    public void setCarId(int carId) {
        this.carId = carId;
    }

    public int getRechargeVal() {
        return rechargeVal;
    }

    public void setRechargeVal(int rechargeVal) {
        this.rechargeVal = rechargeVal;
    }

    public String getRechargeDate() {
        return rechargeDate;
    }

    public void setRechargeDate(String rechargeDate) {
        this.rechargeDate = rechargeDate;
    }
}

代码

ArrayList<GechargeHistoryLists> rechargeHistoryLists = new ArrayList<>();
rechargeHistoryLists.add(new GechargeHistoryLists(1, 100, "2020-10-12 09:35:20"))
rechargeHistoryLists.add(new GechargeHistoryLists(2, 50, "2020-10-12 09:35:20"))

Collections.sort(rechargeHistoryLists, new Comparator<RechargeHistoryList>() {
    @Override
    public int compare(RechargeHistoryList o1, RechargeHistoryList o2) {
        return -(o1.getRechargeVal() - o2.getRechargeVal());//根据充值金额 “降序” 排序
        //return o1.getRechargeVal() - o2.getRechargeVal();//根据充值金额 “升序” 排序
    }
});

如无特别声明,该文章均为 现在网NowTime.cc)原创,转载请遵循 署名-非商业性使用 4.0 国际(CC BY-NC 4.0) 协议,即转载请注明文章来源。


标签: Java, 排序

赞 (0)

添加新评论