Replace For-Loop with Stream::takeWhile

Properties

Property Value
First seen in jSparrow version 3.7.0
Minimum Java version 9
Remediation cost 2 min
Links

Description

The Stream API in Java 9 is extended with the takeWhile 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.

Benefits

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

Requirement & Tags

Requirements

Java 9

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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: