package com.app.main.utils;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/8/23
* Time:下午3:50
*/
public class ReloadSort {
public static class Entity {
public Integer id;
public String name;
public Entity(Integer id, String name) {
this.id = id;
this.name = name;
}
}
public static void main(String[] args) {
Entity entity1 = new Entity(2, "b");
Entity entity2 = new Entity(1, "a");
Entity entity3 = new Entity(3, "c");
List<Entity> entityList = new ArrayList<>();
entityList.add(entity1);
entityList.add(entity2);
entityList.add(entity3);
System.out.println("排序前:" + JSONObject.toJSONString(entityList));
Collections.sort(entityList, new Comparator<Entity>() {
@Override
public int compare(Entity o1, Entity o2) {
if (o1.id > o2.id) {
return 1;
}
if (o1.id < o2.id) {
return -1;
}
return 0;
}
});
System.out.println("排序后" + JSONObject.toJSONString(entityList));
// 附 lambda 写法
Collections.sort(entityList, (o1, o2) -> {
if (o1.id > o2.id) {
return 1;
}
if (o1.id < o2.id) {
return -1;
}
return 0;
});
}
}