【问题标题】:Java : How can we further simplify the java 8 streams logic for FilesJava:我们如何进一步简化文件的 java 8 流逻辑
【发布时间】:2020-12-26 18:25:57
【问题描述】:

我们如何结合下面的 2 个流逻辑:

public void filterRecord(File inputDirectory) throws IOException {

        if (inputDirectory.exists() && !inputDirectory.isDirectory()) {
            List<Path> pathStreams = Files.list(Paths.get(inputDirectory.getAbsolutePath()))
                    .filter(path -> path.toString().endsWith(".csv"))
                    .collect(Collectors.toList());

            for (Path filePath : pathStreams) {

                Files.lines(filePath)
                        .filter(line -> (line != null && !line.isEmpty()))
                        .filter(line -> "10".equals(line.substring(0, line.indexOf(",")).trim()))
                        .forEach(System.out::println);
            }
        }
    }

在上面的代码中,两个 Streams 都参与其中,

  1. 第一个流是使用目录路径过滤具有特定扩展名的文件列表。
  2. 第二个流是从文件中过滤内容并在控制台上打印。

【问题讨论】:

  • ....flatMap(filePath -&gt; Files.lines(filePath)). 会更容易...但你不能,除非你创建一个处理并且不会进一步抛出 IOException 的方法。类似try { return Files.lines(path); } catch (IOException e) { e.printStackTrace(); return Stream.empty(); // or a RuntimeException }
  • 首先,您为什么要使用File? Word 直接与路径。将方法签名设为Path。 2020年几乎不需要使用java.io.File。其次,请研究flatMap对流的操作。

标签: java file java-stream simplify


【解决方案1】:
public void fileStreamsFilter(Path inputDirectoryPath) throws IOException {

    if (Files.exists(inputDirectoryPath) && Files.isDirectory(inputDirectoryPath)) {

        Files.list(inputDirectoryPath).filter(path -> path.toString().endsWith(".csv"))
        .flatMap(path -> {
            try {
                return Files.lines(path);
            } catch (IOException ioException) {
                log.error(ioException.getMessage(), ioException);
            }
            return null;
        })
        .filter(line -> (line != null && !line.isEmpty()))
        .filter(line -> "10".equals(line.substring(0, line.indexOf(",")).trim()))
        .forEach(log::info);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多