我有以下代码来读取文件的行:
String fileName = "dataset/ANC-all-count.txt";
Integer i=0;
//read file into stream, try-with-resources
try (Stream<String> stream = 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++);
但它不能以这种方式工作,所以任何人都可以帮助我如何使它工作?
答案 0 :(得分:6)
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) {
List<String> lines = new ArrayList<String>();
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<String> {
private int count;
@Override
public void accept(String t) {
System.out.println(t);
count++;
}
public int getCount() {
return count;
}
}
}
答案 1 :(得分:5)
使用peek()
和count()
:
i = (int) stream.peek(System.out::println)
.count();
答案 2 :(得分:4)
这里有两个完全不同的东西:
a)
如何在stream.forEach()
中放置多行代码?
b)
我该怎么做才能计算Stream
中的行数?
问题b)
已由其他海报回答;另一方面,一般问题a)
有一个完全不同的答案:
使用(可能多行)lambda表达式或将引用传递给多行方法。
在这种特殊情况下,您要么声明i
字段,要么使用计数器/包装器对象而不是i
。
例如,如果您想在forEach()
明确中有多行,则可以使用
class Counter { // wrapper class
private int count;
public int getCount() { return count; }
public void increaseCount() { count++; }
}
然后
Counter counter = new Counter();
lines.stream().forEach( e -> {
System.out.println(e);
counter.increaseCounter(); // or i++; if you decided i is worth being a field
} );
另一种方法,这次将多行隐藏在方法中:
class Counter { // wrapper class
private int count;
public int getCount() { return count; }
public void increaseCount( Object o ) {
System.out.println(o);
count++;
}
}
然后
Counter counter = new Counter();
lines.stream().forEach( counter::increaseCount );
甚至
Counter counter = new Counter();
lines.stream().forEach( e -> counter.increaseCount(e) );
如果您需要具有多个参数的消费者,则第二种语法会派上用场。第一种语法仍然是最短和最简单的。