Retrieving data in a map

久未见 提交于 2020-05-14 14:12:10

问题


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

I want to create a new Hashmap with key as req_id+name+lowest status no of a specific set.Here set refers to number of rows of a particular ReqId. For e.g.:For reqid 123,we have 7rows constituting as a set. The lowest status no is 1.So value key would be 123 A 1.Similarly, for key 456,I need value 456 B 2.So for sample data hashmap must contain 3 keys with 3 values. I want this for n number of Reqid.The value for each key is arraylist which consists of rows of a specific id as objects.The value is defined in the code.

I just want change in the key of the map.


回答1:


Create a map first outside loop

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

And in loop check and update map for new id set or existing status in larger

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



回答2:


Your main loop boils down to

HashMap<Object, List<Dashboard>> map = new HashMap<>();
HashMap<Integer, Integer> mapStatus = new HashMap<>();
while(rs.next()) {
    Integer id = rs.getInt(1);
    String user = rs.getString(2);
    Dashboard dash = new Dashboard();
    dash.setREQUEST_ID(id);
    dash.setLOGIN_USER(user);
    dash.setPRICE(rs.getInt(3));
    dash.setStatus(rs.getInt(4));
    map.computeIfAbsent(new MapKey(id, user), xKey -> new ArrayList<>()).add(dash);
    mapStatus.merge(id, dash.getPROCESSED(), Math::min);
}

computeIfAbsent will return an existing value or use the function to calculate a value to store it in the map and return. In either case, you can simply apply add to the returned list.

merge will just put the specified value into the map if no value exists, otherwise it will use the specified function to calculate a value from the old and new value. Since Math.min(…,…) will simply return the smaller of the two values, this will be the value to be stored or kept in the map.

Note that in your question’s code, the key was used inconsistently. You used map.put(key, dashRec); to store a new list when necessary, but map.get(id).add(dash); to retrieve the list and add to it. With the computeIfAbsent method, it’s impossible to be inconsistent regarding the key. Further, the dashRec variable became obsolete.

By the way, when MapKey does not carry additional semantics, there are alternative types already capable of fulfilling the purpose. E.g. you could use Array.asList(id, user) or, when you use Java 9+ and can preclude null values, List.of(id, user). Or new AbstractMap.SimpleImmutableEntry(id, user). All of these types implement appropriate equals/hashCode methods.

Array.asList(…) has the advantage of being expandable to more components, SimpleImmutableEntry provides an efficient storage for exactly two components. Java 9’s List.of(…) approach combines both, it allows more components but returns optimized implementations for small numbers. But it forbids null elements.



来源:https://stackoverflow.com/questions/61728984/retrieving-data-in-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!