获取行数,同时使用 lambda 处理行

Getting a count of lines while also processing the lines using lambdas

我正在尝试获取在 BufferedReader 中迭代行的 lambda 处理的行数。

有没有一种方法可以在不编写第二个 lambda 的情况下获得行数?

        final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        inReader.lines().forEach(line -> {
            
            // do something with the line
         });

我也可以在上面的代码块中得到一个计数吗?我正在使用 Java 11.

如果我没理解错的话,你想算上你的兰巴舞。当然,你可以这样做。只需在执行 forEach 之前初始化一个 count 变量并增加 lambda 块中的 count 。像这样:

final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

// fixed the long by this
final AtomicLong counter = new AtomicLong();
inReader.lines().forEach(line -> {
  counter.incrementAndGet();
  // do something with the line
});
// here you can do something with the count variable, like printing it out
System.out.printf("count=%d%n", counter.get());

forEach方法来自Iterable。这绝对不是我选择处理 reader 的方式。我会做这样的事情:

try (BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
  Stream<String> lines = inReader.lines();
  
  long i = lines.peek(line -> {
        
        // do something with the line
     }).count();
  
  System.out.printf("count=%d%n", i);

}

PS: 没有真正测试过,如有错误请指正。

试试这个:

AtomicLong count = new AtomicLong();
lines.stream().forEach(line -> {
    count.getAndIncrement();
    // do something with line;
});