java集合分组

2014-11-24 07:39:58 · 作者: · 浏览: 1

场景:对List中的数组指定索引进行分组


方法一: 这个方法效率较高
[java]
**
* 对指定集合进行分组
* @param list
* @param index 索引、从0开始。
* @return
*/
public static List> groupList(List list,int index){
if(list==null)
return null;
Map> map =new HashMap>();
for (int i = 0; i < list.size(); i++) {
Object key=map.get(list.get(i)[index].toString());
List temp=null;
if(key==null){
temp=new ArrayList();
temp.add(list.get(i));
map.put(list.get(i)[0].toString(), temp);
}
else{
temp=(ArrayList)map.get(list.get(i)[index].toString());
temp.add(list.get(i));
map.put(list.get(i)[0].toString(), temp);
}
}
if(map==null)
return null;
Iterator it= map.keySet().iterator();
Object obj=null;
List> resList=new ArrayList>();
while (it.hasNext()) {
obj=it.next();
if(obj!=null)
resList.add(map.get(obj));
}
return resList;
}

方法二:这个方法的效率很低(使用迭代的方法)

[java]
public List> GetGroupList = new ArrayList>();
/**
* @deprecated
* @param arrayList
* @param index
* @return
*/
public List executeGroupList(List arrayList,int index) {
if (arrayList == null || arrayList.size() == 0)
return null;
List sameList = new ArrayList();
List diffList = new ArrayList();

sameList.add(arrayList.get(0));
arrayList.remove(0);
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i)[index].toString().equals(
sameList.get(0)[index].toString())) {
sameList.add(arrayList.get(i));
} else {
diffList.add(arrayList.get(i));
}
}
GetGroupList.add(sameList);
if (!diffList.isEmpty()) {
executeGroupList(diffList,index);
}
return null;
}

数据量在20W左右时,方法一的效率大大超过方法二,两方法执行时间相差3.9倍左右。

代码还有很多不足之处,欢迎大家批评指正


摘自 wuzongpo的专栏