一、背景介绍
在日常的java开发中,我们在返回一个对象集合时需要按照对象的某个属性或者某些属性进行排序返回给前端进行展示,例如我最近需要返回一个题库集合,需要先根据指定时间排序然后根据创建时间进行排序,在mysql层进行操作比较麻烦而且浪费时间,我们可以通过程序来进行排序。
二、案例代码
// 实体类 public class People { private Integer id; private String name; private Integer topTime;// 置顶时间 private Integer gmtCreate;// 创建时间 public People(Integer id, String name, Integer topTime, Integer gmtCreate) { super(); this.id = id; this.name = name; this.topTime = topTime; this.gmtCreate = gmtCreate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getTopTime() { return topTime; } public void setTopTime(Integer topTime) { this.topTime = topTime; } public Integer getGmtCreate() { return gmtCreate; } public void setGmtCreate(Integer gmtCreate) { this.gmtCreate = gmtCreate; } @Override public String toString() { return "People [id=" + id + ", name=" + name + ", topTime=" + topTime + ", gmtCreate=" + gmtCreate + "]"; } }
// 排序方法 public class PeopleComparator implements Comparator<People>{ @Override public int compare(People o1, People o2) { int result = 0; // 按照置顶时间排序升序(o1,o2位置互换就是降序) int topTimeSeq = o2.getTopTime() - o1.getTopTime(); if(topTimeSeq != 0){ result = (topTimeSeq > 0) ? 3 : -1; }else{ // 按照创建时间排序 topTimeSeq = o2.getGmtCreate() - o1.getGmtCreate(); if(topTimeSeq != 0){ result = (topTimeSeq > 0) ? 2 : -2; } } return result; } }
// 测试 public class PeopleTest { public static void main(String[] args) { List<People> peopleList = new ArrayList<People>(){ { add(new People(1,"tom1",0,1)); add(new People(2,"tom2",2,4)); add(new People(3,"tom3",1,3)); add(new People(4,"tom4",0,6)); add(new People(5,"tom5",0,2)); add(new People(6,"tom6",0,5)); } }; Collections.sort(peopleList,new PeopleComparator()); for(People p:peopleList){ System.out.println(p.toString()); } } }
测试结果
Comparator 多条件比较
class Card { int a; int b; public Card(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public int getB() { return b; } @Override public String toString() { return "Card{" + "a=" + a + ", b=" + b + "}"; } } public class Main { public static void main(String[] args) { List<Card> list = new ArrayList<>(); list.add(new Card(0, 2)); list.add(new Card(1, 1)); list.add(new Card(1, 0)); list.add(new Card(1, 0)); list.add(new Card(2, 0)); System.out.println(list); System.out.println(); Collections.sort(list, new Comparator<Card>() { @Override public int compare(Card c1, Card c2) { // c1 - c2 升序 // c2 - c1 降序 int res1 = c2.b - c1.b; int res2 = c2.a - c1.a; // 当 b相等时比较a, 否则先比较b return res1 == 0 ? res2 : res1; } }); System.out.println(list); } } [Card{a=0, b=2}, Card{a=1, b=1}, Card{a=1, b=0}, Card{a=1, b=0}, Card{a=2, b=0}] [Card{a=0, b=2}, Card{a=1, b=1}, Card{a=2, b=0}, Card{a=1, b=0}, Card{a=1, b=0}]
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/CoderYin/article/details/96994291