【问题标题】:I want to insert ID with the value being a List containing the Records matching that ID我想插入 ID,其值为包含与该 ID 匹配的记录的列表
【发布时间】:2020-04-30 09:55:21
【问题描述】:
        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 组行。

【问题讨论】:

  • 如果我没记错的话,你问的是 123 , [123,A,5] ,[123,A,10], [123,A,15] 类型的数据在地图中吗?
  • 不,我想要 123 作为 key。剩下三行作为 arraylist 中的对象。所以 map 必须有 [id,arraylist]

标签: java sql arraylist hashmap


【解决方案1】:

你可以这样使用地图

        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);
        }

【讨论】:

  • 我正在检查地图是否不包含密钥并将new ArrayList&lt;&gt;() 分配给id,之后我被授予我与该id 相关的ArrayList,然后将对象添加到@987654323 @
  • 我想要123作为key。剩下三行作为arraylist中的对象。所以map必须有[id,arraylist]。那么通过上面的代码可以吗?
  • @Aziz 会的
  • @Aziz 你能批准答案吗
  • 如您所见,我已经初始化了仪表板类型的 Arraylist,所以我想在该特定的 Arraylist 中插入每个唯一 ID 的对象。怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
相关资源
最近更新 更多