2019-01-21_Java对list数据根据某个字段进行分组

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

    • @return 返回分组的结果
      */
      public static List> groupDataByCondition(List srcList, Comparator comparator) {

      List> 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 newGroupList = new ArrayList<>();
           newGroupList.add(srcList.get(i));
           resultList.add(newGroupList);
       }
      

      }

      return resultList;
      }

    public static void main(String[] args) {

     List 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> resultList=ListUtil.groupDataByCondition(jsonObjectList, new Comparator() {
         @Override
         public int compare(JSONObject o1, JSONObject o2) {
             return o1.get("mark_id").equals(o2.get("mark_id")) ? 0 : -1;
         }
     });
    
     System.out.println(resultList);
    

    }

}

你可能感兴趣的:(2019-01-21_Java对list数据根据某个字段进行分组)