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

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

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

  1. final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
  2. inReader.lines().forEach(line -> {
  3. // do something with the line
  4. });

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

xlpyo6sf

xlpyo6sf1#

试试这个:

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

xdyibdwo2#

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

  1. final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
  2. // fixed the long by this
  3. final AtomicLong counter = new AtomicLong();
  4. inReader.lines().forEach(line -> {
  5. counter.incrementAndGet();
  6. // do something with the line
  7. });
  8. // here you can do something with the count variable, like printing it out
  9. System.out.printf("count=%d%n", counter.get());

这个 forEach 方法来自 Iterable . 这绝对不是我选择的处理读者的方式。我会这样做:

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

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

展开查看全部

相关问题