Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over the "entrySet" instead of "keySet"

I’m scanning my code through sonarqube and it shows this code smell "Iterate over the "entrySet" instead of "keySet" ". I tried but can’t figure it out.

Sample code:

public Set<Date> getAccountShiftDate(Map<String, Set<String>> shiftDatesMap, List<Groups> shiftSchedule) {

    // set that has the account shift dates 
    Set<Date> accountShiftDatesTemplate = new Hashset<>();

    // iterate on accounts
    for (String accounts : shiftDatesMap.keySet()) {
        //get group of an account
        Optional <Groups> shiftOptional = shiftList
                                             .stream()
                                             .filter(g -> StringUtils.equalsIgnoreCase(accounts,g.getLongName()))
                                             .findFirst();



..........

Can someone give me a reference to understand this.Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you iterate over shiftDatesMap.keySet() and later on call in your loop shiftDatesMap.get(accounts) you execute an unnecessary get operation for each entry.
Try to read an understand the description of the metioned code smell from SonarQube.

Instead you should use shiftDatesMap.entrySet() which gives you an Entry, i.e. as pair of the key and the value. So if you later on in your loop want to access the value for your given accounts key, you must only access the value from your entry, which is cheaper than calling a get operation on the map for each value.

Before:

for (String accounts : shiftDatesMap.keySet()) {
    Set<String> shiftDates = shiftDatesMap.get(accounts); // unnecessary operation
}

After:

for (Map.Entry<String, Set<String>> entry: shiftDatesMap.entrySet()) {
    String accounts = entry.getKey();
    Set<String> shiftDates = entry.getValue(); // access value for free without 'get' on map

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading