For example, I need to check if there is any data in the map , if they exist, then return otherwise download from the database.

  Map<String, Data> map = Maps.newHashMap(); //Вариант 1 map.containsKey(key) ? map.get(key) : map.put(key, loadFormDatabase(key)); //Вариант 2 Data data = map.get(key); if (data == null) { data = map.put(key, loadFormDatabase(key)); } return data; 

Those. the question is, what will be faster: a preliminary check for the existence of a key in the map , before doing get or just get and checking for != null

  • one
    I apologize, but the first option is some specific syntax? At first it seemed that ternarka. And now I look - no - Sergey Kurenchuk
  • @ Sergey Kurenchuk yes, there was a mistake, corrected, thanks. - Prototype - TV

2 answers 2

Faster, shorter and map.computeIfAbsent(key, SomeClass::loadFromDatabase) is map.computeIfAbsent(key, SomeClass::loadFromDatabase)

    Obviously, the second is faster, because it contains less by one action (the call to containsKey ). On the other hand, it is worth paying attention to whether the dictionary can contain null values. If yes, then the second code will constantly climb behind them into the base, and the first one will work correctly.