java8分组,将Java8流分组而不收集它

在Java 8中,标准的Stream API没有提供不收集元素的分组功能。然而,如果知道要分组的元素总是连续出现在流中,可以使用第三方库StreamEx进行部分归约操作。StreamEx库提供了如`collapse`和`groupRuns`等方法,它们根据给定的条件对相邻元素进行分组,保持流的延迟评估,并且支持并行处理。例如,`groupRuns`可用于创建一个包含相同起始字母的字符串列表的流。
摘要由CSDN通过智能技术生成

Is there any way in Java 8 to group the elements in a java.util.stream.Stream without collecting them? I want the result to be a Stream again. Because I have to work with a lot of data or even infinite streams, I cannot collect the data first and stream the result again.

All elements that need to be grouped are consecutive in the first stream. Therefore I like to keep the stream evaluation lazy.

解决方案

There's no way to do it using standard Stream API. In general you cannot do it as it's always possible that new item will appear in future which belongs to any of already created groups, so you cannot pass your group to downstream analysis until you process all the input.

However if you know in advance that items to be grouped are always adjacent in input stream, you can solve your problem using third-party libraries enhancing Stream API. One of such libraries is StreamEx which is free and written by me. It contains a number of "partial reduction" operators which collapse adjacent items into single based on some predicate. Usually you should supply a BiPredicate which tests two adjacent items and returns true if they should be grouped together. Some of partial reduction operations are listed below:

collapse(BiPredicate): replace each group with the first element of the group. For example, collapse(Objects::equals) is useful to remove adjacent duplicates from the stream.

groupRuns(BiPredicate): replace each group with the List of group elements (so StreamEx is converted to StreamEx>). For example, stringStream.groupRuns((a, b) -> a.charAt(0) == b.charAt(0)) will create stream of Lists of strings where each list contains adjacent strings started with the same letter.

Other partial reduction operations include intervalMap, runLengths() and so on.

All partial reduction operations are lazy, parallel-friendly and quite efficient.

Note that you can easily construct a StreamEx object from regular Java 8 stream using StreamEx.of(stream). Also there are methods to construct it from array, Collection, Reader, etc. The StreamEx class implements Stream interface and 100% compatible with standard Stream API.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值