标签:param static pojo tcl declared catch override set back
应用场景:
在开发中经常遇到要对List<Object>集合进行排序,并且是根据集合中的对象的某个属性来进行排序 --------以下就此做出的解决方案
public static final String DESC = "desc"; public static final String ASC = "asc"; /** * 用途:对一个List集合数组进行排序 * * 说明: * 目前可以对List<java.lang.Class>、List<POJO>、List<Map>这三种类型集合进行排序 * * @param list 排序操作的集合对象 * @param property 指定集合中元素的排序字段,如果集合元素不是对象类型可以传值为null * @param sort 用于指定是升序还是降序 CollectionsUtil.DESC--降序 CollectionsUtil.ASC--升序 * @date 2018.04.27 PM */ public static <T> void sortOnList(List<T> list,final Object property,final String sort){ Collections.sort(list,new Comparator<T>(){ @Override public int compare(T o1, T o2) { Integer a1 = null; Integer a2 = null; if(o1 instanceof Integer) { //针对List<Integer> a1 = (Integer) o1; a2 = (Integer) o2; } else if(o1 instanceof String) { //针对List<String> a1 = Integer.valueOf(o1.toString()); a2 = Integer.valueOf(o2.toString()); } else if(o1 instanceof Map) { //针对List<Map<String,String>类型 Map temp1 = (Map) o1; Map temp2 = (Map) o2; Object object = temp1.get(property); if(object instanceof Integer) { a1 = (Integer) object; a2 = (Integer) temp2.get(property); } else if(object instanceof String){ //根据Map中value来进行排序String类型需要转换 a1 = Integer.parseInt(object.toString()); a2 = Integer.parseInt(temp2.get(property).toString()); } } else { //针对对象类型 Class c1 = o1.getClass(); Class c2 = o2.getClass(); try { Field declaredField1 = c1.getDeclaredField(property.toString()); Field declaredField2 = c2.getDeclaredField(property.toString()); declaredField1.setAccessible(true); declaredField2.setAccessible(true); a1 = Integer.parseInt(declaredField1.get(o1).toString()); a2 = Integer.parseInt(declaredField2.get(o2).toString()); } catch (Exception e) { e.printStackTrace(); } } if(sort.equals(CollectionsUtil.ASC)) //升序 return a1.compareTo(a2); else //降序 return a2.compareTo(a1); } }); }
以下代码原理:
Collections.sort(list,new Comparator<T>(){
@Override
public int compare(T o1, T o2){
}
}
根据集合中的元素,把o1与o2对象的某个数值型属性进行对比:
o1 - o2 >= 0 --- 升序
o1 - o2 < 0 --- 降序
sort方法是对List集合中对象某个属性来进行排序的,例如:
package hello1; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import hello.Student; public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.setId(6); Student s2 = new Student(); s2.setId(66); Student s3 = new Student(); s3.setId(1); Student s4 = new Student(); s4.setId(55); List<Student> list = new ArrayList<>(); list.add(s1); list.add(s2); list.add(s3); list.add(s4); System.out.println("未排序结果:"+ list); //根据Student对象id属性排序 Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getId() - o2.getId(); } }); System.out.println("排序后结果:"+ list); } }
运行结果 ======================》
欢迎路过的哥们提好建议
标签:param static pojo tcl declared catch override set back
原文地址:https://www.cnblogs.com/whqworld/p/8988107.html