-1

Existing Code:

     Map<?, ?> rolePrincipleMap = cnRoleHolder.getRolePrincipalMap();
                Iterator<?> cnRoleIterator = rolePrincipleMap.keySet().iterator();
                  while (cnRoleIterator.hasNext()) {
                    Object cnRole = cnRoleIterator.next();
                  if (!SUBMITTER.equals(cnRole.toString())) {
               ArrayList<?> cnRoleMembersList = (ArrayList<?>) rolePrincipleMap.get(cnRole);
               //operations
}}

Error is in line where ArraList is defined. Pls help to update the code.

  • Does this answer your question? [FindBugs warning: Inefficient use of keySet iterator instead of entrySet iterator](https://stackoverflow.com/questions/12639259/findbugs-warning-inefficient-use-of-keyset-iterator-instead-of-entryset-iterato). SpotBugs is the successor of FindBugs. – Ole V.V. Aug 05 '21 at 10:51

1 Answers1

1

That error warns you that you are accessing the map to retrieve all the keys, and then for some keys, you access the map again to retrieve the value. It is more efficient to retrieve the entries of the map, as each entry has the key and value already:

for ( Map.Entry<?, ?> entry : rolePrincipleMap.entrySet() ) {
   Object cnRole = entry.getKey();
   if (!SUBMITTER.equals(cnRole.toString())) {
           ArrayList<?> cnRoleMembersList = (ArrayList<?>) entry.getValue();
           //operations
   }
}
JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24
  • Thanks for the explanation. I got the logical reason behind this. But still stuck in optimizing the code to get the spotbug resolved. It would be helpful if you can optimize the entire code snippet – Tanvi Sharma Aug 05 '21 at 10:27
  • @TanviSharma I have ammended my answer to include the corresponding version of the code you posted in your question. I lack some context about your code to ensure that my version is exactly what you'd want, but it should be either this or fairly similar. Remember to mark my answer as accepted if it helped to solve your problem. That way other people facing the same issue in the future can find your question and easily see how to solve it. – JustAnotherDeveloper Aug 05 '21 at 10:41