OrderByUtils:(待优化)
package com.icil.report.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ************************************************************************* * <PRE> * @param <E> * @ClassName: : ListUtil * * @Description: : * * @Creation Date : 13 May 2019 2:48:52 PM * * @Author : Sea * * * </PRE> ************************************************************************** */ @SuppressWarnings("all") public class OrderByUtils{ private static Logger LOGGER=LoggerFactory.getLogger(OrderByUtils.class); //####################################################################################################### // order by java 7 && java8 // ###################################################################################################### /** * @Desc: java8 parallelStream * @param colls :需要排序的集合(pojo) * @param firstfiledName :先按排序的字段 * @param secondfiledName ::再按排序的字段 * @return */ // public static <E> List<E> orderby(Collection<E> colls,String firstfiledName,String secondfiledName){ // return colls.parallelStream().sorted(Comparator.comparing(d->getFieldStringValueByName(d,firstfiledName)).thenComparing(d->getFieldStringValueByName(d,secondfiledName))).collect(Collectors.toList()); // } /** * @Desc: java8 parallelStream * @param colls * @param filedName 排序的字段 * @param fieldType 排序的字段的类型 * @return */ public static <E> List<E> orderbyPro(Collection<E> colls,String filedName,Class fieldType){ switch (fieldType.getName()) { case "java.lang.Integer": return colls.parallelStream().sorted(Comparator.comparing(d->(Integer)getFieldValueByName(d,filedName))).collect(Collectors.toList()); case "java.lang.Long": return colls.parallelStream().sorted(Comparator.comparing(d->(Long)getFieldValueByName(d,filedName))).collect(Collectors.toList()); case "java.lang.Double": return colls.parallelStream().sorted(Comparator.comparing(d->(Double)getFieldValueByName(d,filedName))).collect(Collectors.toList()); case "java.util.Date": return colls.parallelStream().sorted(Comparator.comparing(d->(Date)getFieldValueByName(d,filedName))).collect(Collectors.toList()); case "java.lang.Float": return colls.parallelStream().sorted(Comparator.comparing(d->(Float)getFieldValueByName(d,filedName))).collect(Collectors.toList()); case "java.lang.String": return colls.parallelStream().sorted(Comparator.comparing(d->(String)getFieldStringValueByName(d,filedName))).collect(Collectors.toList()); default: return null; } } /** * * @param colls * @param filedName :pojo 的属性名 如 user -->name * @return */ public static <E> List<E> orderby(List<E> colls, String filedName,Class fieldType){ getMyComparator(colls,filedName,fieldType); colls.sort(getMyComparator(colls,filedName,fieldType)); return colls; } /** * 通过属性名称对集合分组 * @Desc:java 8 stream api, list 会过滤掉group by filed 的非空字段 * @param colls 集合必须为对象 eg: List<Employee> * @param fieldName为集合中对象的属性名称 eg: Employee-->name * @return * extends Comparable<T> */ public static final <D> Map<Object ,List<D>> groupByPro(Collection<D> colls ,String fieldName){ //filter // List<D> filterlist = colls.parallelStream().filter(r->getFieldValueByName(r,fieldName)!=null).collect(Collectors.toList()); for (D d : colls) { if(OrderByUtils.getFieldValueByName(d, fieldName)==null){ OrderByUtils.setFieldValueByName(d, fieldName, "null"); } } //group by Map<Object, List<D>> collect = colls.stream().collect(Collectors.groupingBy(r->getFieldValueByName(r,fieldName))); return collect; } /** * 根据属性名称获取属性值 * */ public static Object getFieldValueByName(Object pojo,String fieldName) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = pojo.getClass().getMethod(getter, new Class[] {}); Object value = method.invoke(pojo, new Object[] {}); return value; } catch (Exception e) { LOGGER.error(e.getMessage(),e); return null; } } /** * * @param pojo * @param fieldName * @param value just can be Integer(int) Double(double) Long(ong) Date String */ public static void setFieldValueByName(Object pojo,String fieldName,Object value) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String seter = "set" + firstLetter + fieldName.substring(1); value = Optional.ofNullable(value).orElseGet(()-> new String("null")); String simpleName = value.getClass().getSimpleName(); Class class1; switch (simpleName) { case "Integer": class1=Integer.class; break; case "Double": class1=Double.class; break; case "Long": class1=Long.class; break; case "Date": class1=Date.class; break; default: class1=String.class; break; } Method setmethod = pojo.getClass().getMethod(seter, class1); setmethod.invoke(pojo,value); } catch (Exception e) { LOGGER.error(e.getMessage(),e); } } /** * 根据属性名称获取属性值 (获取String型) * */ public static String getFieldStringValueByName(Object o,String fieldName) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter, new Class[] {}); String value = (String) method.invoke(o, new Object[] {}); return value; } catch (Exception e) { LOGGER.error(e.getMessage(),e); return null; } } public static <E> Comparator<E> getMyComparator(List<E> colls, String filedName,Class fieldType){ Comparator<E> comparator = new Comparator<E>() { @Override public int compare(E o1, E o2) { int result=0; switch (fieldType.getName()) { case "java.lang.Integer": result= getFieldValueByNameAndType(o1,filedName,Integer.class).compareTo(getFieldValueByNameAndType(o2,filedName,Integer.class)); break; case "java.lang.Long": result= getFieldValueByNameAndType(o1,filedName,Long.class).compareTo(getFieldValueByNameAndType(o2,filedName,Long.class)); break; case "java.lang.Double": result= getFieldValueByNameAndType(o1,filedName,Double.class).compareTo(getFieldValueByNameAndType(o2,filedName,Double.class)); break; case "java.util.Date": result= getFieldValueByNameAndType(o1,filedName,Date.class).compareTo(getFieldValueByNameAndType(o2,filedName,Date.class)); break; case "java.lang.Float": result= getFieldValueByNameAndType(o1,filedName,Float.class).compareTo(getFieldValueByNameAndType(o2,filedName,Float.class)); break; case "java.lang.String": result= getFieldValueByNameAndType(o1,filedName,String.class).compareTo(getFieldValueByNameAndType(o2,filedName,String.class)); break; default: result= 0; break; } return result; } }; return comparator; } /** * @param pojo * @param fieldName * @param fieldType * @return */ public static <T> T getFieldValueByNameAndType(Object pojo,String fieldName,Class<T> fieldType) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = pojo.getClass().getMethod(getter, new Class[] {}); T value = (T) method.invoke(pojo, new Object[] {}); return value; } catch (Exception e) { LOGGER.error(e.getMessage(),e); return null; } } /** * @param <T> * @param pojo * @param fieldName * @param fieldType * @return */ public static <T> T getFieldValueByNameAndType(Object pojo,String fieldName) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Field field = pojo.getClass().getDeclaredField(fieldName); // 获取属性 Class<?> type = field.getType(); Method method = pojo.getClass().getMethod(getter, type); T value = (T) method.invoke(pojo, new Object[] {}); return value; } catch (Exception e) { LOGGER.error(e.getMessage(),e); return null; } } }
更多可以参考:http://www.importnew.com/15259.html
Test :
package com.icil.report.jdbc; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import org.junit.Test; import com.icil.report.pojo.GroupByCourier; public class OrderByTest { /** * java7 普通排序 * 多条件组合排序: //先根据NumberOfShipments 排序,然后在更具 Courier 排序 * 从JDK 8开始,我们现在可以把多个Comparator链在一起(chain together)去建造更复杂的比较逻辑: * @throws Exception */ @Test public void orderBYtest1() throws Exception { ArrayList<GroupByCourier> arrayList = new ArrayList<GroupByCourier>(); // GroupByCourier(String courier, Integer numberOfShipments, Integer numberOfSubscriptions) arrayList.add(new GroupByCourier("f",2,3)); arrayList.add(new GroupByCourier("b",10,6)); arrayList.add(new GroupByCourier("a",4,1)); arrayList.add(new GroupByCourier("c",15,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",19,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.sort(Comparator.comparing(GroupByCourier::getNumberOfShipments).thenComparing(GroupByCourier::getCourier)); //先根据NumberOfShipments 排序,然后在更具 Courier 排序 Comparator.comparing(GroupByCourier::getNumberOfShipments).thenComparing(GroupByCourier::getCourier); arrayList.forEach(r->{System.out.println(r.getCourier() +" -- "+r.getNumberOfShipments()+"--"+r.getNumberOfSubscriptions());}); } /** * java7 并行流式排序 * 多条件组合排序: //先根据NumberOfShipments 排序,然后在更具 Courier 排序 ,然后在根据 NumberOfSubscriptions 排序 * 从JDK 8开始,我们现在可以把多个Comparator链在一起(chain together)去建造更复杂的比较逻辑: * @throws Exception */ @Test public void orderBYtest02() throws Exception { ArrayList<GroupByCourier> arrayList = new ArrayList<GroupByCourier>(); // GroupByCourier(String courier, Integer numberOfShipments, Integer numberOfSubscriptions) arrayList.add(new GroupByCourier("f",2,3)); arrayList.add(new GroupByCourier("b",10,6)); arrayList.add(new GroupByCourier("a",4,1)); arrayList.add(new GroupByCourier("c",15,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",19,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); //先根据NumberOfShipments 排序,然后在更具 Courier 排序 ,然后在根据 NumberOfSubscriptions 排序 //List<GroupByCourier> collect = arrayList.parallelStream().sorted(Comparator.comparing(GroupByCourier::getNumberOfShipments).thenComparing(GroupByCourier::getCourier)).collect(Collectors.toList()); List<GroupByCourier> collect = arrayList.parallelStream().sorted(Comparator.comparing(GroupByCourier::getNumberOfShipments).thenComparing(GroupByCourier::getCourier).thenComparing(GroupByCourier::getNumberOfSubscriptions)).collect(Collectors.toList()); System.err.println(collect); collect.forEach(r->{System.out.println(r.getCourier() +" -- "+r.getNumberOfShipments()+"--"+r.getNumberOfSubscriptions());}); } /** * java8 并行流式排序 反转排序 * JDK 8同样提供了一个有用的方法用来反转Comparator(reverse Comparator)——我们可以快速地利用它来反转我们的排序 * 多条件组合排序: //先根据NumberOfShipments 排序,然后在更具 Courier 排序 ,然后在根据 NumberOfSubscriptions 排序 * 从JDK 8开始,我们现在可以把多个Comparator链在一起(chain together)去建造更复杂的比较逻辑: * @throws Exception */ @Test public void orderBYtest04() throws Exception { ArrayList<GroupByCourier> arrayList = new ArrayList<GroupByCourier>(); // GroupByCourier(String courier, Integer numberOfShipments, Integer numberOfSubscriptions) arrayList.add(new GroupByCourier("f",2,3)); arrayList.add(new GroupByCourier("b",10,6)); arrayList.add(new GroupByCourier("a",4,1)); arrayList.add(new GroupByCourier("c",15,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",19,8)); arrayList.add(new GroupByCourier("c",1,8)); arrayList.add(new GroupByCourier("c",1,8)); //先根据NumberOfShipments 排序,然后在更具 Courier 排序 ,然后在根据 NumberOfSubscriptions 排序 (现在是反过来) Comparator<GroupByCourier> compars = Comparator.comparing(GroupByCourier::getNumberOfShipments).thenComparing(GroupByCourier::getCourier).thenComparing(GroupByCourier::getNumberOfSubscriptions); List<GroupByCourier> collect = arrayList.parallelStream().sorted(compars.reversed()).collect(Collectors.toList()); System.err.println(collect); collect.forEach(r->{System.out.println(r.getCourier() +" -- "+r.getNumberOfShipments()+"--"+r.getNumberOfSubscriptions());}); } }