Home > database >  Sonarlint Error says: instead of containsKey use computeIfAbsent
Sonarlint Error says: instead of containsKey use computeIfAbsent

Time:10-23

I have written an application that does not allow duplicated characters. My code is just working fine, however sonar says "instead of containsKey use computeIfAbsent". How can I get over the sonar warning?

My code is below:

if (promoRequest.getCharset() != null) {
    Map<Character, Integer> map = new HashMap<>();
    
    for (char charsetCharacter : promoRequest.getCharset().toCharArray()) {
        if (map.containsKey(charsetCharacter)) {
            throw new BadRequestException(Constants.INCLUDE_MUST_NOT_BE_DUPLICATED);
        }
        map.put(charsetCharacter, 1);
    }
}

I have solved problem

for (char charsetCharacter : promoRequest.getCharset().toCharArray()) {

                if (!map.containsKey(charsetCharacter)) {

                    map.put(charsetCharacter, 1);

                } else {

                    throw new BadRequestException(Constants.CHARSET_CHARACTER_INCLUDE_MUST_NOT_BE_DUPLICATED);
                }

CodePudding user response:

Since you are required to keep the exception there is no benefit in using computeIfAbsent. The reference documentation states the following:

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

This means that whatever mapping function you define it will only be called when the map does not have the key already. Since you simply want to throw an exception when the key is already available using computeIfAbsent is nonsense.

Having said that just keep your code and ignore sonar warning. Keep in mind that sonar analysis is a static one, looking for patterns in your code but that does not always apply to whatever you are trying to do in your code.

If an exception would not be mandatory, then you could do something simpler:

if (promoRequest.getCharset() != null) {
    Map<Character, Integer> map = new HashMap<>();
    
    for (char charsetCharacter : promoRequest.getCharset().toCharArray()) {
        map.putIfAbsent(charsetCharacter, 1);
    }
}
  • Related