2019-01-21_Java对list数据根据某个字段进行分组
2019-01-21 本文已影响0人
kikop
package com.tech.ability.mycommonutils;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
-
Created by kikop on 2019/1/21.
*/
public class ListUtil {/**
-
对list数据进行分组
-
@param srcList
-
@param comparator 条件比较器
-
@param <T>
-
@return 返回分组的结果
*/
public static <T> List<List<T>> groupDataByCondition(List<T> srcList, Comparator<? super T> comparator) {List<List<T>> resultList = new ArrayList<>();
for (int i = 0; i < srcList.size(); i++) {
boolean isFindInCurrentGroups = false;//1.在现有组中查找 for (int groupIndex = 0; groupIndex < resultList.size(); groupIndex++) { if (resultList.get(groupIndex).size() == 0 || comparator.compare(resultList.get(groupIndex).get(0), srcList.get(i)) == 0) { //没有直接添加或者与第j组第一个匹配 resultList.get(groupIndex).add(srcList.get(i)); isFindInCurrentGroups = true; break; } } //2.在现有组中没查找到 if (!isFindInCurrentGroups) { List<T> newGroupList = new ArrayList<>(); newGroupList.add(srcList.get(i)); resultList.add(newGroupList); }
}
return resultList;
}
public static void main(String[] args) {
List<JSONObject> jsonObjectList = new ArrayList<>(); JSONObject jsonObject = new JSONObject(); jsonObject.put("mark_id", 1); jsonObject.put("name", "1_张三"); jsonObjectList.add(jsonObject); jsonObject = new JSONObject(); jsonObject.put("mark_id", 1); jsonObject.put("name", "1_李四"); jsonObjectList.add(jsonObject); jsonObject = new JSONObject(); jsonObject.put("mark_id", 2); jsonObject.put("name", "2_kikop"); jsonObjectList.add(jsonObject); List<List<JSONObject>> resultList=ListUtil.groupDataByCondition(jsonObjectList, new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { return o1.get("mark_id").equals(o2.get("mark_id")) ? 0 : -1; } }); System.out.println(resultList);
}
-
}