Json数组列表中的数据分组排序、组内排序

文章目录

        • 问题描述
        • 方式一:先全部排序,在分组排序
        • 方式二:使用HashMap取出来分组再组内排序
        • 方式三:使用TreeMap取出来分组再组内排序
        • 测试代码及耗时

问题描述

现在有一个用户信息数组,用户信息都在这个数组里,数组中有组号也有排序,现在需要将这些元素按照组号(groupNo)分组并排序,同时组内元素也按照排序字段(sortNum)排序?
示例json数组,分组排序之前

[{
	"userId": "7",
	"userName": "neo1",
	"groupNo": "3",
	"sortNum": "2"
},
{
	"userId": "11",
	"userName": "leo08",
	"groupNo": "3",
	"sortNum": "1"
},
{
	"userId": "15",
	"userName": "zhangsan",
	"groupNo": "3",
	"sortNum": "8"
},
{
	"userId": "1",
	"userName": "neo",
	"groupNo": "1",
	"sortNum": "2"
},
{
	"userId": "2",
	"userName": "leo",
	"groupNo": "1",
	"sortNum": "8"
},
{
	"userId": "3",
	"userName": "zhangsan",
	"groupNo": "1",
	"sortNum": "3"
},
{
	"userId": "4",
	"userName": "neo1",
	"groupNo": "2",
	"sortNum": "6"
},
{
	"userId": "2",
	"userName": "leo08",
	"groupNo": "2",
	"sortNum": "2"
},
{
	"userId": "3",
	"userName": "zhangsan1",
	"groupNo": "2",
	"sortNum": "8"
}]

分组排序之后:

[
    {
        "list":[
            {
                "sortNum":"2",
                "userName":"neo",
                "userId":"1",
                "groupNo":"1"
            },
            {
                "sortNum":"3",
                "userName":"zhangsan",
                "userId":"3",
                "groupNo":"1"
            },
            {
                "sortNum":"8",
                "userName":"leo",
                "userId":"2",
                "groupNo":"1"
            }
        ],
        "groupNo":"1"
    },
    {
        "list":[
            {
                "sortNum":"2",
                "userName":"leo08",
                "userId":"2",
                "groupNo":"2"
            },
            {
                "sortNum":"6",
                "userName":"neo1",
                "userId":"4",
                "groupNo":"2"
            },
            {
                "sortNum":"8",
                "userName":"zhangsan1",
                "userId":"3",
                "groupNo":"2"
            }
        ],
        "groupNo":"2"
    },
    {
        "list":[
            {
                "sortNum":"1",
                "userName":"leo08",
                "userId":"11",
                "groupNo":"3"
            },
            {
                "sortNum":"2",
                "userName":"neo1",
                "userId":"7",
                "groupNo":"3"
            },
            {
                "sortNum":"8",
                "userName":"zhangsan",
                "userId":"15",
                "groupNo":"3"
            }
        ],
        "groupNo":"3"
    }
]

方式一:先全部排序,在分组排序

    /**
     * 方式一:先全部排序,在分组排序
     *
     * @return
     */
    public static List<Map<String, Object>> sortByGroupNo1() {
        String jsonList = "[{\"userId\":\"7\",\"userName\":\"neo1\",\"groupNo\":\"3\",\"sortNum\":\"2\"},{\"userId\":\"11\",\"userName\":\"leo08\",\"groupNo\":\"3\",\"sortNum\":\"1\"},{\"userId\":\"15\",\"userName\":\"zhangsan\",\"groupNo\":\"3\",\"sortNum\":\"8\"},{\"userId\":\"1\",\"userName\":\"neo\",\"groupNo\":\"1\",\"sortNum\":\"2\"},{\"userId\":\"2\",\"userName\":\"leo\",\"groupNo\":\"1\",\"sortNum\":\"8\"},{\"userId\":\"3\",\"userName\":\"zhangsan\",\"groupNo\":\"1\",\"sortNum\":\"3\"},{\"userId\":\"4\",\"userName\":\"neo1\",\"groupNo\":\"2\",\"sortNum\":\"6\"},{\"userId\":\"2\",\"userName\":\"leo08\",\"groupNo\":\"2\",\"sortNum\":\"2\"},{\"userId\":\"3\",\"userName\":\"zhangsan1\",\"groupNo\":\"2\",\"sortNum\":\"8\"}]";
        List<Map<String, Object>> list = (List<Map<String, Object>>) JSON.parse(jsonList);
        List<String> groupNoList = new ArrayList<>();
        //使用比较器,先对分组进行排序
        list.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (!groupNoList.contains(o1.get("groupNo").toString())) {
                    groupNoList.add(o1.get("groupNo").toString());
                }
                if (!groupNoList.contains(o2.get("groupNo").toString())) {
                    groupNoList.add(o1.get("groupNo").toString());
                }
                if (Integer.valueOf(o1.get("groupNo").toString()) > Integer.valueOf(o2.get("groupNo").toString())) {
                    return 1;
                } else if (Integer.valueOf(o1.get("groupNo").toString()) < Integer.valueOf(o2.get("groupNo").toString())) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });

        //定义一个要返回的新的List
        List<Map<String, Object>> returnList = new ArrayList<>();

        //先对分组列表排序
        Collections.sort(groupNoList);

        //对分组进行排序
        for (String groupNo : groupNoList) {
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("groupNo", groupNo);
            newMap.put("list", new ArrayList<Map<String, Object>>());
            for (Map<String, Object> tmp : list) {
                if (groupNo.equals(tmp.get("groupNo").toString())) {
                    List list1 = (List<Map<String, Object>>) newMap.get("list");
                    list1.add(tmp);
                }
            }
            List<Map<String, Object>> list2 = (List<Map<String, Object>>) newMap.get("list");
            list2.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if (Integer.valueOf(o1.get("sortNum").toString()) > Integer.valueOf(o2.get("sortNum").toString())) {
                        return 1;
                    } else if (Integer.valueOf(o1.get("sortNum").toString()) < Integer.valueOf(o2.get("sortNum").toString())) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            returnList.add(newMap);
        }
        return returnList;
    }

本来就写了上面一个方法,但是作为程序员,需要尽可能的提高性能,我接下来又提供了两种实现方式:

方式二:使用HashMap取出来分组再组内排序

    /**
     * 方式二:直接使用HashMap取出来所有分组,在进行分组排序,组内排序
     */
    public static List<Map<String, Object>> sortByGroupNo2() {
        String jsonList = "[{\"userId\":\"7\",\"userName\":\"neo1\",\"groupNo\":\"3\",\"sortNum\":\"2\"},{\"userId\":\"11\",\"userName\":\"leo08\",\"groupNo\":\"3\",\"sortNum\":\"1\"},{\"userId\":\"15\",\"userName\":\"zhangsan\",\"groupNo\":\"3\",\"sortNum\":\"8\"},{\"userId\":\"1\",\"userName\":\"neo\",\"groupNo\":\"1\",\"sortNum\":\"2\"},{\"userId\":\"2\",\"userName\":\"leo\",\"groupNo\":\"1\",\"sortNum\":\"8\"},{\"userId\":\"3\",\"userName\":\"zhangsan\",\"groupNo\":\"1\",\"sortNum\":\"3\"},{\"userId\":\"4\",\"userName\":\"neo1\",\"groupNo\":\"2\",\"sortNum\":\"6\"},{\"userId\":\"2\",\"userName\":\"leo08\",\"groupNo\":\"2\",\"sortNum\":\"2\"},{\"userId\":\"3\",\"userName\":\"zhangsan1\",\"groupNo\":\"2\",\"sortNum\":\"8\"}]";
        List<Map<String, Object>> list = (List<Map<String, Object>>) JSON.parse(jsonList);

        //定义一个要返回的新的List
        List<Map<String, Object>> returnList = new ArrayList<>();
        Iterator iterator = list.iterator();
        Map<String, ArrayList<Map<String, Object>>> hashMap = new HashMap<>();
        while (iterator.hasNext()) {
            Map<String, Object> tmp = (Map<String, Object>) iterator.next();
            String groupNo = tmp.get("groupNo").toString();
            if (hashMap.containsKey(groupNo)) {
                ArrayList<Map<String, Object>> list2 = hashMap.get(groupNo);
                list2.add(tmp);
            } else {
                hashMap.put(groupNo, new ArrayList<>());
                ArrayList<Map<String, Object>> list1 = hashMap.get(groupNo);
                list1.add(tmp);
            }
        }

        //取出来key进行排序
        List<String> keySet = new ArrayList<>(hashMap.keySet());
        Collections.sort(keySet);
        Iterator iterator1 = keySet.iterator();
        while (iterator1.hasNext()) {
            String groupNo = (String) iterator1.next();
            Map<String, Object> newMap = new HashMap<>();
            List<Map<String, Object>> list2 = hashMap.get(groupNo);
            Collections.sort(list2, (o1, o2) -> {
                if (Integer.valueOf(o1.get("sortNum").toString()) > Integer.valueOf(o2.get("sortNum").toString())) {
                    return 1;
                } else if (Integer.valueOf(o1.get("sortNum").toString()) < Integer.valueOf(o2.get("sortNum").toString())) {
                    return -1;
                } else {
                    return 0;
                }
            });
            newMap.put("groupNo", groupNo);
            newMap.put("list", list2);
            returnList.add(newMap);
        }
        return returnList;
    }

方式三:使用TreeMap取出来分组再组内排序

    /**
     * 方式三:使用TreeMap先分组排序,在组内排序
     */
    public static List<Map<String, Object>> sortByGroupNo3() {
        String jsonList = "[{\"userId\":\"7\",\"userName\":\"neo1\",\"groupNo\":\"3\",\"sortNum\":\"2\"},{\"userId\":\"11\",\"userName\":\"leo08\",\"groupNo\":\"3\",\"sortNum\":\"1\"},{\"userId\":\"15\",\"userName\":\"zhangsan\",\"groupNo\":\"3\",\"sortNum\":\"8\"},{\"userId\":\"1\",\"userName\":\"neo\",\"groupNo\":\"1\",\"sortNum\":\"2\"},{\"userId\":\"2\",\"userName\":\"leo\",\"groupNo\":\"1\",\"sortNum\":\"8\"},{\"userId\":\"3\",\"userName\":\"zhangsan\",\"groupNo\":\"1\",\"sortNum\":\"3\"},{\"userId\":\"4\",\"userName\":\"neo1\",\"groupNo\":\"2\",\"sortNum\":\"6\"},{\"userId\":\"2\",\"userName\":\"leo08\",\"groupNo\":\"2\",\"sortNum\":\"2\"},{\"userId\":\"3\",\"userName\":\"zhangsan1\",\"groupNo\":\"2\",\"sortNum\":\"8\"}]";
        List<Map<String, Object>> list = (List<Map<String, Object>>) JSON.parse(jsonList);

        //这里使用treeMap的自动排序机制,对groupNo进行排序
        TreeMap<String, ArrayList<Map<String, Object>>> treeMap = new TreeMap<>();
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> tmp = (Map<String, Object>) iterator.next();
            String groupNo = tmp.get("groupNo").toString();
            if (treeMap.containsKey(groupNo)) {
                ArrayList<Map<String, Object>> list2 = treeMap.get(groupNo);
                list2.add(tmp);
                Collections.sort(list2, (o1, o2) -> {
                    if (Integer.valueOf(o1.get("sortNum").toString()) > Integer.valueOf(o2.get("sortNum").toString())) {
                        return 1;
                    } else if (Integer.valueOf(o1.get("sortNum").toString()) < Integer.valueOf(o2.get("sortNum").toString())) {
                        return -1;
                    } else {
                        return 0;
                    }
                });
            } else {
                treeMap.put(groupNo, new ArrayList<Map<String, Object>>());
                ArrayList<Map<String, Object>> list1 = treeMap.get(groupNo);
                list1.add(tmp);
            }
        }
        //定义一个要返回的新的List
        List<Map<String, Object>> returnList = new ArrayList<>();
        Iterator iter = treeMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map<String, Object> newMap = new HashMap<>();
            Map.Entry<String, ArrayList<Map<String, Object>>> entry = (Map.Entry<String, ArrayList<Map<String, Object>>>) iter.next();
            String keyGroupNo = entry.getKey();
            newMap.put("groupNo", keyGroupNo);
            newMap.put("list", entry.getValue());
            returnList.add(newMap);
        }
        return returnList;
    }

测试代码及耗时

    /**
     * 花费时间测试
     */
    public static void costTime() {
        System.out.println("sortByGroupNo1排序结果:" + JSON.toJSONString(sortByGroupNo1()));
        System.out.println("sortByGroupNo2排序结果:" + JSON.toJSONString(sortByGroupNo2()));
        System.out.println("sortByGroupNo3排序结果:" + JSON.toJSONString(sortByGroupNo3()));

        int loopTimes = 100000;
        long startTime1 = System.currentTimeMillis();
        for (int i = 0; i < loopTimes; i++) {
            sortByGroupNo1();
        }
        System.out.println(loopTimes + "次循环,sortByGroupNo1耗时:" + (System.currentTimeMillis() - startTime1) + "ms");

        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i < loopTimes; i++) {
            sortByGroupNo2();
        }
        System.out.println(loopTimes + "次循环,sortByGroupNo2耗时:" + (System.currentTimeMillis() - startTime2) + "ms");

        long startTime3 = System.currentTimeMillis();
        for (int i = 0; i < loopTimes; i++) {
            sortByGroupNo3();
        }
        System.out.println(loopTimes + "次循环,sortByGroupNo3耗时:" + (System.currentTimeMillis() - startTime3) + "ms");
    }

结果如下

sortByGroupNo1排序结果:[{"list":[{"sortNum":"2","userName":"neo","userId":"1","groupNo":"1"},{"sortNum":"3","userName":"zhangsan","userId":"3","groupNo":"1"},{"sortNum":"8","userName":"leo","userId":"2","groupNo":"1"}],"groupNo":"1"},{"list":[{"sortNum":"2","userName":"leo08","userId":"2","groupNo":"2"},{"sortNum":"6","userName":"neo1","userId":"4","groupNo":"2"},{"sortNum":"8","userName":"zhangsan1","userId":"3","groupNo":"2"}],"groupNo":"2"},{"list":[{"sortNum":"1","userName":"leo08","userId":"11","groupNo":"3"},{"sortNum":"2","userName":"neo1","userId":"7","groupNo":"3"},{"sortNum":"8","userName":"zhangsan","userId":"15","groupNo":"3"}],"groupNo":"3"}]
sortByGroupNo2排序结果:[{"list":[{"sortNum":"2","userName":"neo","userId":"1","groupNo":"1"},{"sortNum":"3","userName":"zhangsan","userId":"3","groupNo":"1"},{"sortNum":"8","userName":"leo","userId":"2","groupNo":"1"}],"groupNo":"1"},{"list":[{"sortNum":"2","userName":"leo08","userId":"2","groupNo":"2"},{"sortNum":"6","userName":"neo1","userId":"4","groupNo":"2"},{"sortNum":"8","userName":"zhangsan1","userId":"3","groupNo":"2"}],"groupNo":"2"},{"list":[{"sortNum":"1","userName":"leo08","userId":"11","groupNo":"3"},{"sortNum":"2","userName":"neo1","userId":"7","groupNo":"3"},{"sortNum":"8","userName":"zhangsan","userId":"15","groupNo":"3"}],"groupNo":"3"}]
sortByGroupNo3排序结果:[{"list":[{"sortNum":"2","userName":"neo","userId":"1","groupNo":"1"},{"sortNum":"3","userName":"zhangsan","userId":"3","groupNo":"1"},{"sortNum":"8","userName":"leo","userId":"2","groupNo":"1"}],"groupNo":"1"},{"list":[{"sortNum":"2","userName":"leo08","userId":"2","groupNo":"2"},{"sortNum":"6","userName":"neo1","userId":"4","groupNo":"2"},{"sortNum":"8","userName":"zhangsan1","userId":"3","groupNo":"2"}],"groupNo":"2"},{"list":[{"sortNum":"1","userName":"leo08","userId":"11","groupNo":"3"},{"sortNum":"2","userName":"neo1","userId":"7","groupNo":"3"},{"sortNum":"8","userName":"zhangsan","userId":"15","groupNo":"3"}],"groupNo":"3"}]
100000次循环,sortByGroupNo1耗时:3433ms
100000次循环,sortByGroupNo2耗时:1338ms
100000次循环,sortByGroupNo3耗时:992ms

你可能感兴趣的:(算法,java基础知识)