openrewrite / openrewrite/rewrite-static-analysis

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

Open
#626 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

recipe
Dominant language
Java
Stars
62
Forks
112
Avg merge
1d 19h
Merged PRs (30d)
40

Description

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);
       }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file, test, or entry point is named in the issue. Start by examining the repository’s existing Java recipe implementations and recipe tests for similar loop transformations; done means the described indexed loop can be safely rewritten to an enhanced for-each loop under the listed preconditions, with coverage for the examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.