Java-收集消费者?
有没有一种功能性的方法来首先收集流的元素,然后立即将集合传递给消费者?换句话说,一种在将所有流元素作为集合而不是一个接一个地应用终端操作之前等待流结束的构造?
例如,您是否可以将以下内容实现为单行:
Stream<Event> stream = // a stream of events
List<Event> list = stream.collect(Collectors.toList());
doProcessEvents(list);
作为一种解决方法,我可以 (ab) 使用Collectors.collectingAndThen()和 aFunction来实现我正在寻找的结果:
Function<List<Event>, Void> processingFunction = (list -> {
doProcessEvents(list);
return null;
});
Stream<Event> stream = // a stream of events
stream.collect(Collectors.collectingAndThen(Collectors.toList(), processingFunction);
我考虑过的其他替代方案(但不起作用)是如果该collectingAndThen()方法有一个Consumer作为第二个参数,例如,Collectors.collectingAndThen(Collector downstream, Consumer consumer)或者如果Consumer接口有一个finish()在流中的最后一个元素被消耗后执行的方法:
class EventConsumer implements Consumer<Event> {
private final List<Event> list = new LinkedList<>();
@Override
public void accept(Event ev) {
events.add(ev);
}
public void finish() {
doProcessEvents(events);
}
}
// usage
Stream<Event> stream = // a stream of events
stream.forEach(new EventConsumer());
这种方法的问题是事件会保存在内部列表中,但finish()不会调用该方法。它只需稍作修改即可工作,但仍然没有单线:
Stream<Event> stream = // a stream of events
EventConsumer consumer = new EventConsumer()
stream.forEach(consumer);
consumer.finish();
回答
有没有一种功能性的方法来首先收集流的元素,然后立即将集合传递给消费者?
Consumer.accept(T t)直接调用方法即可:
Stream<Event> stream = ...
Consumer<List<Event>> consumer = ...
consumer.accept(stream.collect(Collectors.toList()));