【问题标题】:Java and HashMap - how to add to existing values?Java 和 HashMap - 如何添加到现有值?
【发布时间】:2014-01-27 01:06:13
【问题描述】:

我目前正在开发一个客户端/服务器应用程序,并且我正在使用 HashMap 来识别每个客户端。客户端将两个值传递给服务器 - idx。我使用id 作为我的键,对于HashMap 中的每个元素,我想使用x 的值将具有匹配键id 的特定元素添加到值中。

我有以下代码:

HashMap<Integer, Integer> clients = new HashMap<Integer, Integer>();

int x;
sock = serv.accept();
in = new ObjectInputStream(sock.getInputStream());
in2 = sock.getInputStream();
out = new ObjectOutputStream(sock.getOutputStream());

int id = in2.read();
System.out.println("id = " + id);
Object o = in.readObject();         
System.out.println("Server received " + o);
if (o instanceof Integer) {
    x = ((Integer) o).intValue();
    clients.put(id, 0 + x); //doesn't work, I need to be able to add to the existing value instead of overwriting the value

} else if (o instanceof String) {
    clients.put(id, 0);
}
out.writeObject(clients.get(id));
out.flush();

有人可以帮我吗?

【问题讨论】:

  • 添加是指在数学上下文中添加,或者您想添加一个与该键映射的值
  • 我的意思是在数学方面。例如,如果客户端第一次通过 1 和 3,服务器应该返回 3。如果客户端第二次通过 1 和 5,服务器应该返回 8。但是,如果客户端通过 2 和 7,服务器应该返回 7,因为 2 与 1 不同。

标签: java hashmap client-server


【解决方案1】:
Integer previousValue = clients.get(id);
if(previousValue == null) previousValue = 0;
clients.put(id, previousValue + x);

【讨论】:

    【解决方案2】:

    您需要从地图中读取值,然后您可以添加类似

    Integer resultantValue = x;
    Integer previousValue = clents.get(id);
    if(previousValue!=null){
      resultantValue+=previousValue;
    }
    
    clients.put(id, resultantValue);
    

    【讨论】:

      【解决方案3】:

      在 Java 8 或更高版本中,您可以使用 Merge。

      int newValue = 3;
      clients.merge(id, newValue, Integer::sum);
      

      【讨论】:

        【解决方案4】:

        你可以这样做:

        Integer value = new Integer(0);
        
        if (clients.containsKey(id)) {
            value = clients.get(id);        
        }
        value.add(new Integer(x) + value);
        clients.put(id, value);
        

        【讨论】:

        • 我不是要添加两个元素,而是要根据数学上下文添加值。
        • 我已根据您的说明修改了答案。
        【解决方案5】:

        最好的方法可能是创建一个专门针对整数的 HashMap 扩展,并使用专门用于以您指定的方式添加到特定值的方法,如下所示:

        import java.util.HashMap;
        
        public class IntegerHashMap extends HashMap<Integer,Integer>{
        
            public void addValueToKey(Integer key, Integer valueToAdd){
                Integer originalValue = this.get(key);
                Integer newValue = originalValue + valueToAdd;
                this.put(key, newValue);
            }
        
        }
        

        如果需要,这将使再次使用代码变得容易,从外观上看,它很有可能,并且具有仅使用正确类型的 HashMap 的额外好处。

        【讨论】:

        • 最好覆盖HashMap#put
        • @Prince 我考虑过,但该函数的用途与put() 不同,我认为put() 可能仍然是必要的。
        猜你喜欢
        • 2020-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多