Java如何根据实体指定字段值对其List进行排序详解
更新时间:2024年07月02日 09:56:08 作者:熙子XIZI
在Java项目中可能会遇到给出一些条件,将List元素按照给定条件进行排序的情况,这篇文章主要给大家介绍了关于Java如何根据实体指定字段值对其List进行排序的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
本文记录在开发过程,如何使用Java对List中的实体指定的字段进行排序。
一、先准备个实体PO
public class Student { private String name; private String age; private String score; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } }
二、简易版本,利用比较器来实现排序
public class SortUtil { public static void main(String[] args) { List<Student> students = new ArrayList<>(); Student studentA = new Student(); studentA.setName("a"); studentA.setAge("16"); studentA.setScore("95"); Student studentB = new Student(); studentB.setName("b"); studentB.setAge("16"); studentB.setScore("83"); Student studentC = new Student(); studentC.setName("c"); studentC.setAge("16"); studentC.setScore("90"); students.add(studentA); students.add(studentB); students.add(studentC); System.out.println("-----排序前----"); for (Student student : students) { System.out.println("学生:" + student.getName() + "的分数为[" + student.getScore() + "]"); } System.out.println(); //排序-------------比较器来实现排序 Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { BigDecimal data1 = new BigDecimal(o1.getScore()); BigDecimal data2 = new BigDecimal(o2.getScore()); return data2.compareTo(data1); } }); //------------------------------ System.out.println("-----排序后----"); for (Student student : students) { System.out.println("学生:" + student.getName() + "的分数为[" + student.getScore() + "]"); } }
测试结果:
三、封装成通用的方法类调用
import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.*; /** * @ClassName: SortUtil * @Author: XIZI * @Description: 排序 */ public class SortUtil { private static Logger logger = Logger.getLogger(SortUtil.class); /** * 排序 * * @param list 需要排序的list * @param filedName 字段名 * @param ascFlag 是否升序 * @param clazz 排序的类 * @param <T> */ public static <T> void sort(List<T> list, String filedName, boolean ascFlag, Class<T> clazz) { //通过比较器来实现排序 list.sort(new Comparator<T>() { @Override public int compare(T o1, T o2) { String data1s = ""; String data2s = ""; Field[] fields = getAllFields(clazz); for (Field field : fields) { // 设置字段可访问(必须,否则报错) field.setAccessible(true); if (field.getName().equals(filedName)) { try { data1s = field.get(o1).toString(); data2s = field.get(o2).toString(); } catch (IllegalAccessException e) { logger.error("排序出现异常:", e); return 0; } break; } } BigDecimal data1 = new BigDecimal(data1s); BigDecimal data2 = new BigDecimal(data2s); if (ascFlag) { //升序 return data1.compareTo(data2); } else { //降序 return data2.compareTo(data1); } } }); } public static Field[] getAllFields(Class<?> clazz){ List<Field> fieldList = new ArrayList<>(); while (clazz != null && !clazz.getName().toLowerCase().equals("java.lang.object")){ fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } Field[] fields = new Field[fieldList.size()]; return fieldList.toArray(fields); } }
测试用例:
public static void main(String[] args) { List<Student> students = new ArrayList<>(); Student studentA = new Student(); studentA.setName("a"); studentA.setAge("16"); studentA.setScore("95"); Student studentB = new Student(); studentB.setName("b"); studentB.setAge("16"); studentB.setScore("83"); Student studentC = new Student(); studentC.setName("c"); studentC.setAge("16"); studentC.setScore("90"); students.add(studentA); students.add(studentB); students.add(studentC); System.out.println("-----排序前----"); for (Student student : students) { System.out.println("学生:" + student.getName() + "的分数为[" + student.getScore() + "]"); } System.out.println(); //调用排序方法执行降序 SortUtil.sort(students, "score", false, Student.class); System.out.println("-----排序后----"); for (Student student : students) { System.out.println("学生:" + student.getName() + "的分数为[" + student.getScore() + "]"); } }
测试结果如预期一致。
附:指定条件排序
实现 List 排序有多种方法,本文总结以下几种。
调用 list sort 方法,实现比较器接口进行排序
package com.example.demo.help; import java.util.*; public class ListSortTest { public static void main(String[] args) { List<String> rules = new ArrayList<>(); rules.add("30003"); rules.add("20002"); rules.add("10001"); rules.add("40004"); rules.add("60006"); rules.add("50005"); Map<String, Integer> ruleUpper = new HashMap<>(); ruleUpper.put("10001", 1); ruleUpper.put("20002", 2); ruleUpper.put("30003", 3); ruleUpper.put("40004", 4); rules.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return ruleUpper.getOrDefault(o1, Integer.MAX_VALUE) - ruleUpper.getOrDefault(o2, Integer.MAX_VALUE); } }); System.out.println(rules); // [10001, 20002, 30003, 40004, 60006, 50005] } }
调用 list sort 方法,通过 lambda 表达式实现排序
package com.example.demo.help; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ListSortTest { public static void main(String[] args) { List<String> rules = new ArrayList<>(); rules.add("30003"); rules.add("20002"); rules.add("10001"); rules.add("40004"); rules.add("60006"); rules.add("50005"); Map<String, Integer> ruleUpper = new HashMap<>(); ruleUpper.put("10001", 1); ruleUpper.put("20002", 2); ruleUpper.put("30003", 3); ruleUpper.put("40004", 4); rules.sort((o1, o2) -> (ruleUpper.getOrDefault(o1, Integer.MAX_VALUE) - ruleUpper.getOrDefault(o2, Integer.MAX_VALUE))); System.out.println(rules); // [10001, 20002, 30003, 40004, 60006, 50005] } }
通过 Collections sort 方法,实现比较器接口进行排序
package com.example.demo.help; import java.util.*; public class ListSortTest { public static void main(String[] args) { List<String> rules = new ArrayList<>(); rules.add("30003"); rules.add("20002"); rules.add("10001"); rules.add("40004"); rules.add("60006"); rules.add("50005"); Map<String, Integer> ruleUpper = new HashMap<>(); ruleUpper.put("10001", 1); ruleUpper.put("20002", 2); ruleUpper.put("30003", 3); ruleUpper.put("40004", 4); Collections.sort(rules, new Comparator<String>() { @Override public int compare(String o1, String o2) { return ruleUpper.getOrDefault(o1, Integer.MAX_VALUE) - ruleUpper.getOrDefault(o2, Integer.MAX_VALUE); } }); System.out.println(rules); // [10001, 20002, 30003, 40004, 60006, 50005] } }
总结
到此这篇关于Java如何根据实体指定字段值对其List进行排序的文章就介绍到这了,更多相关Java实体指定字段值对List排序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论