List根据指定key分组

来源:互联网 发布:linux bash alias 编辑:程序博客网 时间:2024/05/19 16:07
public interface Key<K, V> {

K get(V v);

}

public class Group {


public static <K, V> Map<K, List<V>> create(List<V> list, Key<K, V> key) {
Map<K, List<V>> m = new HashMap<K, List<V>>();
create(m, list, key);
return m;
}

public static <K, V> void create(Map<K, List<V>> m, List<V> list, Key<K, V> key) {
        m.clear();
for (V o : list) {
K k = key.get(o);
List<V> l = (List<V>) m.get(k);
if (l == null) {
l = new ArrayList<V>();
m.put(k, l);
}
l.add(o);
}
}
}

0 0
原创粉丝点击