Sonarlint提示用computeIfAbsent替代containsKey,如何消除该告警?
问题处理方案
告警原因说明
SonarLint弹出该告警,是因为代码中对同一个key先后执行containsKey、put两次哈希查找操作,存在冗余性能开销,规则要求用单次computeIfAbsent调用合并两个操作。你两次实现都保留了containsKey调用,因此告警未消除。
解决方案
方案1:按照告警要求使用Map compute相关方法实现
直接用compute方法合并存在判断、插入、异常抛出逻辑,完全消除containsKey调用:
if (promoRequest.getCharset() != null) { Map<Character, Integer> map = new HashMap<>(); for (char charsetCharacter : promoRequest.getCharset().toCharArray()) { map.compute(charsetCharacter, (key, oldValue) -> { if (oldValue != null) { // oldValue非空说明字符已存在,直接抛出异常 throw new BadRequestException(Constants.CHARSET_CHARACTER_INCLUDE_MUST_NOT_BE_DUPLICATED); } return 1; }); } }
方案2:更换更适配判重场景的HashSet实现(更推荐)
你的场景本质是字符去重校验,不需要存储冗余的value值,使用HashSet实现更简洁,性能更优,也不会触发该告警:
if (promoRequest.getCharset() != null) { Set<Character> charSet = new HashSet<>(); for (char charsetCharacter : promoRequest.getCharset().toCharArray()) { // add方法返回false代表字符已存在于集合中 if (!charSet.add(charsetCharacter)) { throw new BadRequestException(Constants.CHARSET_CHARACTER_INCLUDE_MUST_NOT_BE_DUPLICATED); } } }
内容的提问来源于stack exchange,提问作者mark whalf
相关产品推荐
相关产品推荐

