如果键已经存在,增加地图的价值?

Increment the value of the map if key is already present?

我有一个映射,其中我将字节总数存储为键并计数为值。如果密钥已经存在于我的地图中,我需要将计数增加 1。如果密钥不存在,则从 1.

开始

我有以下代码 -

Map<Integer, Integer> userList = new HashMap<Integer, Integer>();
for (String userId : listOfUsers) {
        String sql = "select * from test_table where user_id='"+ userId + "';";
    try {
        SimpleStatement query = new SimpleStatement(sql);
        ResultSet res = session.execute(query);

        int totalBytes = 0;
        Iterator<Row> rows = res.iterator();
        while (rows.hasNext()) {
            Row r = rows.next();

            ByteBuffer client_value = r.getBytes("client_value");

            int returned = client_value.remaining();
            totalBytes = totalBytes + returned;
        }

        // does this look right?
        userList.put(totalBytes, userList.get(totalBytes) + 1);

    } catch (Exception e) {
        // log an error
    }
}

每当我第一次 运行 时,我的 userList.put 命令都会收到 NPE。我做错了什么吗?此代码将在单线程中。

没有,

userList.put(totalBytes, userList.get(totalBytes) + 1);

你第一次运行这个,userList.get(totalBytes)将return一个当然不能递增的空对象。

可以固定为

Integer val = userList.get(totalBytes);
if (val == null) {
   val = new Integer ();
}
val = val + 1;

不,如果密钥不存在,您将得到 NullPointerException。那是因为表达式 userList.get(totalBytes) + 1 会尝试将 null 拆箱为 int.

正确的方法是在添加之前进行 null 检查。

Integer bytes = userList.get(totalBytes);
userList.put(totalBytes, bytes == null ? 1 : bytes + 1);

你可以改变

userList.put(totalBytes, userList.get(totalBytes) + 1);

userList.put(totalBytes, userList.getOrDefault(totalBytes, 0) + 1);

如果您使用的是 Java 8,则无需手动进行空值检查。

试试下面这个..

userList.put(totalBytes,(userList.contains(totalBytes)?(userList.get(totalBytes)+1):1));