List 分组实现
首先创建实体类
import java.io.Serializable;
public class Foo implements Serializable{
private static final long serialVersionUID = 1395253695450566358L;
private String code;
private String name;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[code=" + code + ", name=" + name + "]";
}
}
写工具类
创建排序规则接口(按照什么条件排序)
public interface GroupBy <T>{
T groupby(Object obj);
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Util {
@SuppressWarnings("unchecked")
public static <K extends Comparable<K>, V> Map<K, Collection<V>> group(Collection<V> colls, GroupBy<?> gb){
if(colls == null || colls.isEmpty()){
return null;
}
if(gb == null){
return null;
}
Iterator<V> iter = colls.iterator();
Map<K,Collection<V>> map = new HashMap<K, Collection<V>>();
while(iter.hasNext()){
V v = iter.next();
K k = (K) gb.groupby(v);
if(map.containsKey(k)){
map.get(k).add(v);
}else{
ArrayList<V> list = new ArrayList<V>();
list.add(v);
map.put(k, list);
}
}
return map;
}
public static void main(String[] args) {
ArrayList<Foo> list = new ArrayList<Foo>();
Foo foo1 = new Foo("001","abc1");
list.add(foo1);
Foo foo2 = new Foo("001","abc2");
list.add(foo2);
Foo foo3 = new Foo("002","abc3");
list.add(foo3);
Foo foo4 = new Foo("002","abc4");
list.add(foo4);
Foo foo5 = new Foo("003","abc5");
list.add(foo5);
Foo foo6 = new Foo("004","abc6");
list.add(foo6);
Map<String, Collection<Foo>> map = Util.group(list, new GroupBy<String>(){
public String groupby(Object obj) {
Foo foo = (Foo) obj;
return foo.getCode();
}
});
System.out.println(map.toString());
}
}
输出结果
{004=[[code=004, name=abc6]], 001=[[code=001, name=abc1], [code=001, name=abc2]], 002=[[code=002, name=abc3], [code=002, name=abc4]], 003=[[code=003, name=abc5]]}