Use BufferedReader::lines

Properties

Property Value
First seen in jSparrow version 3.3.0
Minimum Java version 8
Remediation cost 5 min

Description

Java 8 introduced BufferedReader::lines to generate a stream of elements representing lines in the BufferedReader. This rule, replaces While-Loops and For-Loops that are using BufferedReader::readLine to iterate through lines of a file by a stream generated with BufferedReader::lines.

Benefits

Using streams instead of loops improves the readability and makes the code more compact.

Requirement & Tags

Requirements

Java 8

Code Changes

While Loops

Pre

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    String line;
    while((line = bufferedReader.readLine()) != null) {
        consume(line);
    }
}

Post

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    bufferedReader.lines().forEach(line -> {
        consume(line);
    });
}

For Loops with initializer

Pre

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    for(String line; (line = bufferedReader.readLine()) != null;) {
        consume(line);
    }
}

Post

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    bufferedReader.lines().forEach(line -> {
        consume(line);
    });
}

For Loops without initializer

Pre

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    String line;
    for(; (line = bufferedReader.readLine()) != null;) {
        consume(line);
    }
}

Post

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {			
    bufferedReader.lines().forEach(line -> {
        consume(line);
    });
}

Automatic Application of This Rule

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