我有以下代码来读取文件的行:
String fileName = "dataset/ANC-all-count.txt"; Integer i=0; //read file into stream, try-with-resources try (Streamstream = Files.lines(Paths.get(fileName), StandardCharsets.ISO_8859_1)) { stream.forEach(System.out::println); i++; } catch (IOException e) { e.printStackTrace(); } System.out.println("count is : "+i);
但问题是我需要放入i++
以下行:
stream.forEach(System.out::println);
所以我想要这样的东西:
stream.forEach(System.out::println; i++);
但它不能以这种方式工作,所以任何人都可以帮助我如何使它工作?
该forEach
方法采用任何实现的类的实例Consumer
.所以这是一个使用自定义Consumer
实现来跟上计数的例子.以后你可以叫getCount()
上Consumer
执行得到计数.
import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ConsumerDemo { public static void main(String[] args) { Listlines = new ArrayList (); lines.add("line 1"); lines.add("line 2"); MyConsumer countingConsumer = new MyConsumer(); lines.stream().forEach(countingConsumer); System.out.println("Count: " + countingConsumer.getCount()); } private static class MyConsumer implements Consumer { private int count; @Override public void accept(String t) { System.out.println(t); count++; } public int getCount() { return count; } } }
使用peek()
和count()
:
i = (int) stream.peek(System.out::println) .count();