javaiteratorsonarqubekeysetentryset

Performance - Inefficient use of keySet iterator instead of entrySet iterator


This piece of code throws the error This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup. Kindly guide me how to rephrase it

if (docPropertiesMap != null) {
        Iterator<String> properties = docPropertiesMap.keySet().iterator();
        IDocProperty[] docProperties = new IDocProperty[docPropertiesMap
                .size()];
        int iArrIndex = 0;

        while (properties.hasNext()) {
            String strPropName = properties.next();
            String[] propValue = docPropertiesMap.get(strPropName);

            IDocProperty docProperty = (IDocProperty) FDMAFactory
                    .getDataObject("DocProperty");
            docProperty.setPropertyName(strPropName);
            docProperty.setArrPropertyValues(propValue);
            docProperties[iArrIndex++] = docProperty;
        }
        metadata.setArrDocProperties(docProperties);
        return metadata;
    }

Solution

  • This is SonarQube warning coming from FindBugs.

    You can rewrite your code like this:

    if (docPropertiesMap != null) {
        IDocProperty[] docProperties = new IDocProperty[docPropertiesMap.size()];
        int iArrIndex = 0;
    
        for (Map.Entry<String, String[]> entry : docPropertiesMap.entrySet()) {
            String strPropName = entry.getKey();
            String[] propValue = entry.getValue();
    
            IDocProperty docProperty = (IDocProperty) FDMAFactory.getDataObject("DocProperty");
            docProperty.setPropertyName(strPropName);
            docProperty.setArrPropertyValues(propValue);
            docProperties[iArrIndex++] = docProperty;
        }
        metadata.setArrDocProperties(docProperties);
        return metadata;
    }