Java 8流条件处理 [英] Java 8 streams conditional processing

查看:124
本文介绍了Java 8流条件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣将流分成两个或更多个子流,并以不同的方式处理这些元素。例如,(大)文本文件可能包含A类行和B类行,在这种情况下我想做类似的事情:

I'm interested in separating a stream into two or more substreams, and processing the elements in different ways. For example, a (large) text file might contain lines of type A and lines of type B, in which case I'd like to do something like:

File.lines(path)
.filter(line -> isTypeA(line))
.forEachTrue(line -> processTypeA(line))
.forEachFalse(line -> processTypeB(line))

前一个是我尝试抽象的情况。实际上我有一个非常大的文本文件,其中每一行都是针对正则表达式进行测试的;如果该行通过,则处理它,而如果它被拒绝,那么我想更新一个计数器。对拒绝字符串的进一步处理是我不仅仅使用过滤器的原因。

The previous is my attempt at abstracting the situation. In reality I have a very large text file where each line is testing against a regex; if the line passes, then it is processed, whereas if it is rejected, then I want to update a counter. This further processing on rejected strings is why I don't simply use filter.

有没有合理的方法用流做这个,还是我必须回退到循环? (我希望这也是并行运行的,所以溪流是我的第一选择。)

Is there any reasonable way to do this with streams, or will I have to fallback to loops? (I would like this to run in parallel as well, so streams are my first choice).

推荐答案

Java 8流不是'旨在支持这种操作。来自 jdk

Java 8 streams weren't designed to support this kind of operation. From the jdk:


应该只对一个流进行操作(调用中间或终端流操作)。例如,这排除了分叉流,其中相同的源提供两个或更多个管道,或者同一个流的多个遍历。

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream.

如果你可以将它存储在内存中,你可以使用 Collectors.partitioningBy 如果你只有两种类型并使用 Map< Boolean,列表> 。否则使用 Collectors.groupingBy

If you can store it in memory you can use Collectors.partitioningBy if you have just two types and go by with a Map<Boolean, List>. Otherwise use Collectors.groupingBy.

这篇关于Java 8流条件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆