首页 > 解决方案 > 我想插入 ID,其值为包含与该 ID 匹配的记录的列表

问题描述

        ArrayList<Dashboard> dashRec=new ArrayList<Dashboard>();
        HashMap<Object, List<Dashboard>> map = new HashMap<>();
        int x=0;
        Dashboard dash=new Dashboard();
        while(rs.next()) {
            if (x == 0){
                x=rs.getInt(1);
            }
            int  y = rs.getInt(1);
            if(x==y) {
            dashRec=new ArrayList<Dashboard>();
            dash=new Dashboard();
            dash.setREQUEST_ID(rs.getInt(1));
            dash.setLOGIN_USER(rs.getString(2));
            dash.setPRICE(rs.getInt(3));
            dashRec.add(dash);

            }
            if(y!=x){
                dash.getREQUEST_ID();
                dash.getLOGIN_USER();
                map.put(dash,dashRec);
                x=y;
                //1st arraylist is inserted in map.
                ///
            }

我想插入 ID,其值为包含与该 ID 匹配的记录的列表。我已经为第一组行完成了它。如何为 n 行执行此操作?假设对于接下来的两行,我希望在 map 中添加另一个列表。同样,对于我想要逻辑的 n 组行。

SQL 数据库

标签: javasqlarraylisthashmap

解决方案


你可以像这样使用地图

        Map<Integer, List<Dashboard>> map = new HashMap<>();
        while (rs.next()) {
            Integer id = rs.getInt(1);
            if (!map.containsKey(id)) {
                map.put(id, new ArrayList<>());
            }
            Dashboard dash = new Dashboard();
            dash.setREQUEST_ID(id);
            dash.setLOGIN_USER(rs.getString(2));
            dash.setPRICE(rs.getInt(3));
            map.get(id).add(dash);
        }

推荐阅读