首页 > 解决方案 > 在地图中检索数据

问题描述

public class Dashboard {
int REQUEST_ID, PRICE, Status;           
String LOGIN_USER;

public int getREQUEST_ID() {
 return REQUEST_ID;
 }

 public void setREQUEST_ID(int rEQUEST_ID) {
  REQUEST_ID = rEQUEST_ID;
 }

  //all getters and setters
  public class MapKey {
  private Integer id;
  private String name;

   public MapKey(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  @Override Hashcode and equals
public class DBConnection {
 public ArrayList<Dashboard>  getStoreResult() {
   ArrayList<Dashboard> dashRec;

 try{
  Class.forName("");
  Connection con=DriverManager.getConnection("");
  Statement st=con.createStatement();
  ResultSet rs=st.executeQuery("");

  HashMap<Object, List<Dashboard>> map = new HashMap<>();
  HashMap<Integer, Integer> mapStatus = new HashMap<>();
  while (rs.next()) {
    Integer id = rs.getInt(1);
    MapKey key = new MapKey(rs.getInt(1), rs.getString(2));
    if (!map.containsKey(key)) {
        dashRec= new ArrayList<Dashboard>();
        map.put(key, dashRec);
    }
    Dashboard dash = new Dashboard();
    dash.setREQUEST_ID(id);
    dash.setLOGIN_USER(rs.getString(2));
    dash.setPRICE(rs.getInt(3));
    dash.setStatus(rs.getInt(4));/////STATUS
    map.get(id).add(dash);
    if (!mapStatus.containsKey(id) || mapStatus.get(id)>dash.getPROCESSED()){
                mapStatus.put(id, dash.getPROCESSED());
            } 
    }
   }
  }
 }

我想创建一个新的 Hashmap,其键为 req_id+name+lowest status no 的特定集合。这里的集合是指特定 ReqId 的行数。例如:对于 reqid 123,我们有 7 行构成一个集合。最低状态号是 1。所以值键将是 123 A 1。类似地,对于键 456,我需要值 456 B 2。所以对于示例数据哈希图必须包含 3 个键和 3 个值。我想要 n 个 Reqid。每个键的值是 arraylist,它由作为对象的特定 id 的行组成。值在代码中定义。

我只想更改地图的键。

数据库

标签: javasqlobjectcollectionshashmap

解决方案


首先在外循环创建地图

Map<Integer, Integer> mapStatus = new HashMap<>();

并在循环中检查和更新地图以获取更大的新 ID 集或现有状态

while (rs.next()) {
    ... // your existing codes
    if (!mapStatus.containsKey(id) || mapStatus.get(id)>dash.getStatus()) {
        mapStatus.put(id, dash.getStatus());
    } 
}

推荐阅读