簡體   English   中英

如何為現有密鑰添加值

[英]How to add value to an existing key

我正在使用循環語句從結果集中添加映射中的鍵和值,如果該鍵已存在,則更新該鍵並添加其值。

這是我的代碼:

Map<Integer, Integer> item_id = new Hashmap<Integer , Integer>();

for (i=0 ; i<roomtype_id.length(); i++) {
  String query ="SELECT item_id , quantity from amenities_tb where roomtype_id = '"+roomtype_id.get(i)+"'"
  PreparedStatement pst = connection.preparedStatement(query);
  Result Set rs = pst.executeQuery();

  while(rs.next()) {
    if (item_id.containskey(rs.getInt(1))) {
      // update this key and add to its existing value
    }
    else {
      item_id.put(rs.getInt(1),rs.getInt(2));
    }
  }

在java 8中,你可以創建完整的if else只是一個語句:

item_id.compute (rs.getInt (1), (key, old) -> (old == null ? 0 : old)+rs.getInt (2));

從地圖中獲取舊值,將值添加到地圖中,然后將其放回地圖中。

   Map<Integer, Integer> item_id = new Hashmap<Integer , Integer>();
   for(i=0 ; i<roomtype_id.length(); i++)
   {
      String query ="SELECT item_id , quantity from amenities_tb where roomtype_id = '"+roomtype_id.get(i)+"'"
      PreparedStatement pst = connection.preparedStatement(query);
      Result Set rs = pst.executeQuery();

      while(rs.next()){
                if(item_id.containskey(rs.getInt(1))){
                    // update this key and add to its existing value
                    int value = item_id.get(rs.getInt(1));
                    value += rs.getInt(2);
                    item_id.put(rs.getInt(1), value);
                }else{
                          item_id.put(rs.getInt(1),rs.getInt(2));
                }
      }

試着用這個:

  while(rs.next()){
            if(item_id.containskey(rs.getInt(1))){
             Integer value = item_id.get(rs.getInt(1));
             if(value == null) 
               value = 0;
              item_id.put(rs.getInt(1), value);
                      // update this key and add to its existing value
            }
  item_id.put(id, previousValue + x);

為此,您需要將您的值設為集合,例如: Map<Integer, List<Integer>>

或者更簡單的解決方案是使用google guava庫: Multimap<Integer, Integer>

在Java 8中,您可以使用merge

Integer key = rs.getInt(1);
Integer value = rs.getInt(2);
item_id.merge(key, value, Integer::sum);

此外,請確保keyvalue 不是空的

如果指定的鍵尚未與值關聯或與null關聯,則將其與給定的非空值關聯。 否則,將相關值替換為給定重映射函數的結果,或者如果結果為null則刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM