Skip to content

Recipe to use for-each kind of a loop when iterating over a collection #626

@greg-at-moderne

Description

@greg-at-moderne

What problem are you trying to solve?

Code readability.

When iterating over a collection one can avoid having a "low-level" kind of a loop with explicit index, but rather use the for-each kind of a loop syntax.

What precondition(s) should be checked before applying this recipe?

  • Java >= 5, which I guess we can take for granted.
  • No code in the for loop body which would use the index variable for some other purposes
  • The iteration follows the convention of 0 to .size(), etc.

Describe the situation before applying the recipe

        List<String> names = List.of("Alice", "Bob", "Charlie");

        // Traditional for-loop with index
        for (int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }

Describe the situation after applying the recipe

       List<String> names = List.of("Alice", "Bob", "Charlie");
       for (String name : names) {
           System.out.println(name);
       }

Metadata

Metadata

Labels

Type

No type

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions