Java中List根据某一字段排序

上午茶c 2019-02-27 10:29:40
int max = 0; //中间比大小值 for(int i = 0;i<result.size();i++){ max = Integer.parseInt(result.get(i).get("需要排序字段名").toString()); for(int j = i;j<result.size();j++){ int compare = Integer.parseInt(result.get(j).get("需要排序的字段名").toString()); if(compare>max){ Map<String,Object> temp = result.get(i); result.set(i, result.get(j)); result.set(j,temp); max = compare; //若下一个值比上一个值大把最大值更新 } } }
...全文
2762 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
上午茶c 2021-09-18
精选
  • 打赏
  • 举报
回复

首先排序这东西有很多现成的接口可以直接实现, 我们只是学一下里面的思想

       // 1.模拟生成数据
        List<Map<String, Object>> result = new ArrayList<>();
        int minValue = 1990, maxValue = 2021 ;
        for (int i = 1; i <= 10; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("Model" , "robot" + i + "号");
            map.put("No" , (int)(Math.random()*(maxValue - minValue) + minValue));
            result.add(map);
        }

        // 2.进行排序后比较替换
        int max = 0; //中间比大小值
        for (int i = 0; i < result.size(); i++) {
            //max = Integer.parseInt(result.get(i).get("需要排序字段名").toString());
            max = Integer.parseInt(result.get(i).get("No").toString());
            for (int j = i; j < result.size(); j++) {
                //int compare = Integer.parseInt(result.get(j).get("需要排序的字段名").toString());
                int compare = Integer.parseInt(result.get(j).get("No").toString());
                //if (compare < max) { //从小到大排序
                if (compare > max) {   //从大到小排序
                    Map<String, Object> temp = result.get(i);
                    result.set(i, result.get(j));
                    result.set(j, temp);
                    max = compare; //若下一个值比上一个值大把最大值更新
                }
            }
        }
        System.out.println(result.toString());
    }**

别闹腰不好 2019-03-01
  • 打赏
  • 举报
回复
Comparator 接口 了解一下

51,395

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧