# Replace For-Loop with Stream::takeWhile

# Description

The Stream API in Java 9 is extended with the takeWhile (opens new window) method to get the prefix of a stream. This rule replaces the enhanced for-loops iterating over the prefix of a collection with Stream::takeWhile.

Requirements

Java 9

# Benefits

Applying this rule results in better readability and more compact code.

# Tags

# Code Changes

# Iterating over a List

Pre

List<User> users = findAllSorted();
for(User user : users) {
    if(!isImportantCustomer(user)) {
        break;
    }
    attachDiscount(user);
}

Post

List<User> users = findAllSorted();
users.stream()
    .takeWhile(user -> isImportantCustomer(user))
    .forEach(user -> applyDiscount(user));

# Iterating over a Map

Pre

Map<Integer, User> users = findAllSorted();
for(Map.Entry<Integer, User> entry : users.entrySet()) {
    if(!isEarlyCustomerId(entry.getKey())) {
        break;
    }
    User user = entry.getValue();
    attachDiscount(user);
}

Post

Map<Integer, User> users = findAllSorted();
users.entrySet()
    .stream()
    .takeWhile(entry -> isEarlyCustomerId(entry.getKey()))
    .forEach(entry -> {
        User user = entry.getValue();
        attachDiscount(user);
    });

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID EnhancedForLoopToStreamTakeWhile
First seen in jSparrow version 3.7.0
Minimum Java version 9
Remediation cost 2 min