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

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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