排序在业务逻辑中是非常重要的功能,下面是一个基于 Java 的自定义排序实践。
Comparator 是 Java 中的接口,位于 java.util 包下。
在 Java JDK 中默认的是升序,即
"> return 1"
"< return -1"
"= return 0"
因此,降序就是
"> return -1"
"< return 1"
"= return 0"
- import com.alibaba.fastjson.JSONObject;
-
- import java.util.*;
-
-
- class TestTest {
-
- public static void main(String[] args) {
- JSONObject jsonObject1 = new JSONObject();
- jsonObject1.put("a", 2);
- jsonObject1.put("b", 2);
-
- JSONObject jsonObject2 = new JSONObject();
- jsonObject2.put("a", 1);
- jsonObject2.put("b", 3);
-
- JSONObject jsonObject3 = new JSONObject();
- jsonObject3.put("a", 4);
- jsonObject3.put("b", 0);
-
- JSONObject jsonObject4 = new JSONObject();
- jsonObject4.put("a", 4);
- jsonObject4.put("b", -1);
-
- List
list = new ArrayList<>(); - list.add(jsonObject1);
- list.add(jsonObject2);
- list.add(jsonObject3);
- list.add(jsonObject4);
-
- System.out.println(list);
-
- Comparator
comparator = new MyComparator(); - list.sort(comparator);
- System.out.println(list);
-
- }
- }
-
-
- class MyComparator implements Comparator
{ -
- @Override
- public int compare(JSONObject o1, JSONObject o2) {
- int o1a = o1.getIntValue("a");
- int o2a = o2.getIntValue("a");
- int o1b = o1.getIntValue("b");
- int o2b = o2.getIntValue("b");
- if (o1a > o2a) {
- return 1;
- } else if (o1a < o2a) {
- return -1;
- } else {
- if (o1b > o2b) {
- return -1;
- } else if (o1b < o2b) {
- return 1;
- } else {
- return 0;
- }
- }
- }
- }
以上是自定义排序的一种简单实践,具体还需根据实践进行更复杂的排序。