傳統方式:ListUtil.java

public class ListUtil{ private static Logger LOGGER=LoggerFactory.getLogger(ListUtil.class); /** * 分組依據接口,用於集合分組時,獲取分組 * T為要groupBy屬性是類型,這個返回值為要groupBy的屬性值 */ public interface GroupBy<T> { T groupBy(Object obj) ; } /** * 通過屬性對集合分組 * @param colls * @param gb * @return * extends Comparable<T> */ public static final <T,D> Map<T ,List<D>> groupBy(Collection<D> colls ,GroupBy<T> gb){ Map<T ,List<D>> map = new HashMap<T, List<D>>(); Iterator<D> iter = colls.iterator() ; while(iter.hasNext()) { D d = iter.next() ; T t = gb.groupBy(d) ; if(map.containsKey(t)) { map.get(t).add(d) ; } else { List<D> list = new ArrayList<D>() ; list.add(d) ; map.put(t, list) ; } } return map ; } /** * 通過屬性名稱對集合分組 * @param colls * @param fieldName為集合中對象的屬性名稱 * @return * extends Comparable<T> */ public static final <T,D> Map<T ,List<D>> groupBy(Collection<D> colls ,String fieldName){ return groupBy(colls,new GroupBy<T>(){ @Override public T groupBy(Object obj){ Object v=getFieldValueByName(obj,fieldName); return (T)v; } }); } /** * 根據屬性名稱獲取屬性值 * */ public static Object getFieldValueByName(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[] {}); Object value = method.invoke(o, new Object[] {}); return value; } catch (Exception e) { LOGGER.error(e.getMessage(),e); return null; } }}
參考:https://blog.csdn.net/frankenjoy123/article/details/70739800
java stream:
ReportDetailInfo.java
@Data @ToString public class ReportDetailInfo { private String account; private String orderNo; private String customer; private String courier; private String courierBillNo; private String subscribedDate; // private String bookingNO; }
過濾:
List<ReportDetailInfo> list = ediPdJdbcTemplate.query(sql,new BeanPropertyRowMapper(ReportDetailInfo.class)) ; list.get(0).setCourier(null);
//並發流 list = list.parallelStream().filter(r->r.getCourier()!=null).collect(Collectors.toList());
//串行流: list.stream.filter(r->r.gerCourier()!=null).collect(Collectors.toList());
分組:
Map<String, List<ReportDetailInfo>> collect = list.parallelStream().collect(Collectors.groupingBy(ReportDetailInfo::getCourier));
Set<Entry<String, List<ReportDetailInfo>>> entrySet = collect.entrySet(); for (Entry<String, List<ReportDetailInfo>> entry : entrySet) { System.err.println(entry.getKey()+"---> size"+entry.getValue().size() ); }
統計:
參數1:根據那個字段分組
參數2:數據統計
Map<String, Long> collect = list.parallelStream().collect(Collectors.groupingBy(ReportDetailInfo::getCourier,Collectors.counting()));
Set<Entry<String, Long>> entrySet = collect.entrySet(); for (Entry<String, Long> entry : entrySet) { System.err.println(entry.getKey()+"---> size"+entry.getValue() ); }