List按某个字段排序


List按某个字段排序

方式一:

需要jdk1.8以上 

  1. List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());

方式二:

  1.   import java.lang.reflect.Method;
  2.   import java.util.Collections;
  3.   import java.util.Comparator;
  4.   import java.util.List;
  5.   
  6.   public class SortList<T> {
  7.   
  8.   /**
  9.   * @param targetList
  10.   * 目标排序List
  11.   * @param sortField
  12.   * 排序字段
  13.   * @param sortMode
  14.   * 排序方式
  15.   */
  16.   @SuppressWarnings({ "unchecked", "rawtypes" })
  17.   public void sort(List<T> targetList, final String sortField, final String sortMode) {
  18.  Collections.sort(targetList, new Comparator() {
  19.   
  20.   public int compare(Object obj1, Object obj2) {
  21.     int retVal = 0;
  22.     try {
  23.    Method method1 = ((T) obj1).getClass().getMethod(sortField, null);
  24.    Method method2 = ((T) obj2).getClass().getMethod(sortField, null);
  25.     if (sortMode != null && "desc".equals(sortMode)) {
  26.    retVal = method2.invoke(((T) obj2), null).toString()
    1.    .compareTo(method1.invoke(((T) obj1), null).toString()); // 倒序
  27.  } else {
    1.    retVal = method1.invoke(((T) obj1), null).toString()
    2.    .compareTo(method2.invoke(((T) obj2), null).toString()); // 正序
  28.  }
  29.  } catch (Exception e) {
    1.     throw new RuntimeException();
    2. }
    3.     return retVal;
  30.  
    }
  31.  
     
  32.  
    });
  33.  
    }
  34.  
     
  35.  }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM