Key existence check in HashMap

后端 未结 10 1975
走了就别回头了
走了就别回头了 2020-11-27 09:03

Is checking for key existence in HashMap always necessary?

I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is b

10条回答
  •  清歌不尽
    2020-11-27 09:58

    You can also use the computeIfAbsent() method in the HashMap class.

    In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:

    HashMap> map = new HashMap<>();
    map.computeIfAbsent("checking_account", key -> new ArrayList<>())
       .add(100)
       .add(200);
    

    This way you don't have to check to see if the key checking_account exists or not.

    • If it does not exist, one will be created and returned by the lambda expression.
    • If it exists, then the value for the key will be returned by computeIfAbsent().

    Really elegant!

提交回复
热议问题