lambda - Java 8 Stream 每 100 行读取一次文件

标签 lambda java-8 stream

假设我有一个巨大的文件,我想每行读取 100 行并执行一项操作。 (我想合并 100 行并发送休息请求)

在 Java 7 中,我会执行如下操作。

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();       
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

我们可以在这里利用 Java 8 Stream 吗? 我知道我们可以做这样的事情,但它在每一行而不是 100 行上运行。所以我认为 foreach 不是这里的选择。

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

最佳答案

如果您不喜欢上述方法,您可以简单地使用第二种方法,但您无法并行创建部分流,因为您必须按顺序读取。例如:

split(Paths.get("file"), 100).forEach(this::sendRequest);

void sendRequest(List<String> each) {
  // then you must send the rest request in parallel here
}
<小时/>
Stream<List<String>> split(Path path, int limit) throws IOException {
    // skip the remaining lines if its size < limit
    return split(Files.lines(path), limit, true);
}

<T> Stream<List<T>> split(Stream<T> source,
                          int limit, boolean skipRemainingElements) {

    //variables just for printing purpose
    Spliterator<T> it = source.spliterator();
    long size = it.estimateSize();
    int c = it.characteristics();// characteristics

    return stream(new AbstractSpliterator<List<T>>(size, c) {
        private int thresholds = skipRemainingElements ? limit : 1;

        @Override
        @SuppressWarnings("StatementWithEmptyBody")
        public boolean tryAdvance(Consumer<? super List<T>> action) {
            List<T> each = new ArrayList<>(limit);

            while (each.size() < limit && it.tryAdvance(each::add)) ;

            if (each.size() < thresholds) return false;

            action.accept(each);
            return true;
        }

    }, false).onClose(source::close);
}

关于lambda - Java 8 Stream 每 100 行读取一次文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935165/

相关文章:

java - 我可以从没有显式变量的 lambda 表达式创建 Comparator 对象吗?

javafx 8 兼容性问题 - FXML 静态字段或方法

scala - 如何将回溯算法转换为流?

c++ - 如何通过 C++ 中的升压套接字发送 ostream?

java - 如何在 Java 中映射 lambda 表达式

c# - ForEach lambda 表达式可以有可选的返回类型吗

Java Stream API——如何减少一个循环来减少

java - reduce() 方法在 Java 8 中是如何工作的?

java - BOS/BIS 取得进展

c++ - 使用 lambda 修改由打包参数标识的引用?