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

查看:20
本文介绍了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))

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

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.否则使用 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天全站免登陆