← 中文资源

简体中文版本

String lines 空行过滤

lines() 按行终止符拆成流,strip() 去掉首尾空白,isBlank() 过滤纯空白行,最后用 repeat 画分隔线:清洗日志或命令输出不需要手写 split 正则。

阅读英文原文

实现说明

逻辑集中在类 LogCleaner和函数 main里。

使用要点

  • 跑完文件,输出里会留下标记——kept。

常见问题

运行「String lines 空行过滤」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 kept 标签标明各步骤。

核心语句

.filter(line -> !line.isBlank())
.toList();

代码示例

import java.util.List;

public class LogCleaner {

    public static void main(String[] args) {
        String raw = """
                INFO  boot complete
                DEBUG trace noise

                   WARN  disk 81% full

                ERROR job failed once
                """;

        // lines() 按行终止符拆成流;strip() 去首尾空白;isBlank() 判定纯空白行
        List<String> cleaned = raw.lines()
                .map(String::strip)
                .filter(line -> !line.isBlank())
                .toList();

        cleaned.forEach(line -> System.out.println(line.toLowerCase()));

        String report = String.join(" | ", cleaned);
        System.out.println(report);
        System.out.println("=".repeat(report.length()));
        System.out.println("kept " + cleaned.size() + " of " + raw.lines().count() + " lines");
    }
}