Skip to content

Migrate to Lambda forEach from Traditional for Loop #512

Open
@Pankraz76

Description

@Pankraz76

✨ Migrate to Lambda forEach from Traditional for Loop

Migrating from traditional for loops to lambda-based forEach improves code readability and aligns with modern Java functional programming practices.

✅ In this case, we reduced 75% overhead, going from 4 LOC to just 1 LOC — a clear win in simplicity and maintainability.


🚀 Benefits of this change:

  • Cleaner, more concise code (often reducing to a single line)
  • Better use of the Java Streams API
  • 🔗 Improved cohesion and reduced coupling
  • 🧼 Follows clean code principles and promotes functional design

🔗 Pull Request: #16874
📸 Preview


🔧 Refactor Origin

This change is a combination of two improvements:

  • S1488: Local variables should not be declared and then immediately returned or thrown
    📌 Related Issue: #16488

  • Replacing old-school for loops with a modern .forEach lambda pattern


🧠 Code Example

// ❌ Before: Traditional for-loop
for (Item item : items) {
    process(item);
}

// ✅ After: Lambda forEach
items.forEach(item -> process(item));

📉 This change significantly reduces boilerplate while preserving the original behavior.


🔗 References

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Recipes Wanted

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions