Java 代码实现分组
Java 代码实现分组:
原理实际是利用map的key的唯一性来作为分组关键点,然后使用list封装内容,核心代码如下,调用过程中,需要重新实现groupBy接口,即说明是根据什么来分组的,根据实际需要,实现自己的接口。
public interface GroupBy<T> { T groupby(Object obj) ; } /** * * @param colls * @param gb * @return */ public static final <T extends Comparable<T> ,D> Map<T ,List<D>> group(Collection<D> colls ,GroupBy<T> gb){ if(colls == null || colls.isEmpty()) { System.out.println("参数不能为空!"); return null ; } if(gb == null) { System.out.println("参数不能为空!"); return null ; } Iterator<D> iter = colls.iterator() ; Map<T ,List<D>> map = new HashMap<T, List<D>>() ; 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 ; }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了