java—获取行数,同时使用lambdas处理行

x4shl7ld  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(339)

我试图得到一个lambda在bufferedreader中迭代行所处理的行数。
有没有一种方法可以不写第二个lambda就得到一个计数呢?

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

        inReader.lines().forEach(line -> {

            // do something with the line
         });

我能在上面的代码块中也得到一个计数吗?我正在使用Java11。

xlpyo6sf

xlpyo6sf1#

试试这个:

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

xdyibdwo2#

如果我没听错的话,你就得算你的羔羊。当然,你能做到。只是初始化一个 count 在执行 forEach 并增加 count 在你的lambda街区。这样地:

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 . 这绝对不是我选择的处理读者的方式。我会这样做:

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);

}
附言:没有真正测试这个,所以纠正我,如果我做错了。

相关问题