在java中对象进行排序,排序的属性是string,我们只需要实现Comparator接口,然后实现比较的方式。
public class StringSort {
public static void main(String[] args) {
test1();
}
// 方式1:
public static void test1(){
JSONObject jsonObject = JSONObject.parseObject("{\"result\":[{\"id\":\"A1001\",\"text\":\"程序员\"}, {\"id\":\"G1003\",\"text\":\"建筑师\"}, {\"id\":\"D1005\",\"text\":\"设计师\"}, {\"id\":\"G1009\",\"text\":\"自由职业\"}, {\"id\":\"E2007\",\"text\":\"学生\"}, {\"id\":\"C1009\",\"text\":\"教师\"}, {\"id\":\"A1002\",\"text\":\"医生\"}, {\"id\":\"B1005\",\"text\":\"律师\"}, {\"id\":\"F2009\",\"text\":\"架构师\"}]}");
List<JSONObject> list = JSONArray.parseArray(jsonObject.getString("result"), JSONObject.class);
list.forEach(System.out::println);
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
return o1.getString("id").compareTo(o2.getString("id") ); // 升序排列
// return - o1.getString("id").compareTo(o2.getString("id") ); // 降序排列
}
});
System.out.println("--------------排序后--------------------");
list.forEach(System.out::println);
}
// 方式2:
public static void test2(){
JSONObject jsonObject = JSONObject.parseObject("{\"result\":[{\"id\":\"A1001\",\"text\":\"程序员\"}, {\"id\":\"G1003\",\"text\":\"建筑师\"}, {\"id\":\"D1005\",\"text\":\"设计师\"}, {\"id\":\"G1009\",\"text\":\"自由职业\"}, {\"id\":\"E2007\",\"text\":\"学生\"}, {\"id\":\"C1009\",\"text\":\"教师\"}, {\"id\":\"A1002\",\"text\":\"医生\"}, {\"id\":\"B1005\",\"text\":\"律师\"}, {\"id\":\"F2009\",\"text\":\"架构师\"}]}");
List<JSONObject> list = JSONArray.parseArray(jsonObject.getString("result"), JSONObject.class);
list.forEach(System.out::println);
Collections.sort(list, (o1, o2) -> {
// return o1.getString("id").compareTo(o2.getString("id") ); // 升序排列
return - o1.getString("id").compareTo(o2.getString("id") ); // 降序排列
});
System.out.println("--------------排序后--------------------");
list.forEach(System.out::println);
}
// 方式3:
public static void test3(){
JSONObject jsonObject = JSONObject.parseObject("{\"result\":[{\"id\":\"A1001\",\"text\":\"程序员\"}, {\"id\":\"G1003\",\"text\":\"建筑师\"}, {\"id\":\"D1005\",\"text\":\"设计师\"}, {\"id\":\"G1009\",\"text\":\"自由职业\"}, {\"id\":\"E2007\",\"text\":\"学生\"}, {\"id\":\"C1009\",\"text\":\"教师\"}, {\"id\":\"A1002\",\"text\":\"医生\"}, {\"id\":\"B1005\",\"text\":\"律师\"}, {\"id\":\"F2009\",\"text\":\"架构师\"}]}");
List<JSONObject> list = JSONArray.parseArray(jsonObject.getString("result"), JSONObject.class);
list.forEach(System.out::println);
Collections.sort(list, Comparator.comparing(o -> o.getString("id")));
System.out.println("--------------排序后--------------------");
list.forEach(System.out::println);
}
}