Skip to content

Instantly share code, notes, and snippets.

@hayukleung
Created February 14, 2017 01:17
Show Gist options
  • Save hayukleung/73b8b9f37b2d3e126ab3fe6da0e7600b to your computer and use it in GitHub Desktop.
Save hayukleung/73b8b9f37b2d3e126ab3fe6da0e7600b to your computer and use it in GitHub Desktop.
集合分组方法
package com.chargerlink.app.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* chargerlink_v3
* com.chargerlink.app.utils
* CollectionUtils.java
*
* by hayukleung
* at 2017-02-08 14:36
*/
/**
* Java集合通用方法
*/
public class CollectionUtils {
/**
* 依据K将List<V>分组
*
* @param list
* @param <V>
* @return a list
*/
public static <V extends Groupable> List<List<V>> groupAsList(List<V> list) {
List<List<V>> result = new ArrayList<>();
Map<Integer, List<V>> group = groupAsMap(list);
for (Integer key : group.keySet()) {
result.add(group.get(key));
}
return result;
}
/**
* 依据K将List<V>分组
*
* @param list
* @param <V>
* @return a map
*/
public static <V extends Groupable> Map<Integer, List<V>> groupAsMap(List<V> list) {
Map<Integer, List<V>> group = new HashMap<>();
if (null == list || 0 == list.size()) {
return group;
}
for (V v : list) {
if (!group.containsKey(v.getGroupableKey())) {
List<V> vList = new ArrayList<>();
vList.add(v);
group.put(v.getGroupableKey(), vList);
} else {
group.get(v.getGroupableKey()).add(v);
}
}
return group;
}
public static interface Groupable {
int getGroupableKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment