分组值序列 [英] Group sequences of values

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

问题描述

我想知道是否有任何漂亮的方式使用新的Stream API来分组值序列。

I'm wondering if there's in any nifty way to use the new Stream APIs to "group" sequences of values.

例如。将一系列整数拆分为整数组,其中每个组都是一个递增的数字序列:

e.g. split a series of integers, into groups of integers where each group is an ascending number sequence:

IntStream seq = IntStream.of(1, 2, 3, -1, -1, 1, 2, 1, 2);
IntFunction next = i -> i + 1;

// DESIRED OUTPUT: [[1,2,3], [-1], [-1], [1,2], [1,2]]


推荐答案

不幸的是,Stream API不太适合解决涉及相关操作的问题在Stream元素上,就像这个一样。

Unfortunately, the Stream API is not very well suited to tackle problems that involve dependant operations on the Stream element, like this one.

但是,你可以使用 StreamEx 库:

public static void main(String[] args) {
    IntStream seq = IntStream.of(1, 2, 3, -1, -1, 1, 2, 1, 2);
    IntUnaryOperator next = i -> i + 1;

    List<List<Integer>> result = 
        IntStreamEx.of(seq).boxed().groupRuns((i1, i2) -> next.applyAsInt(i1) == i2).toList();

    System.out.println(result); // prints "[[1, 2, 3], [-1], [-1], [1, 2], [1, 2]]"
}

这个分组为 List 所有连续的整数,其中第二个整数等于 next 函数应用于第一个。最后,此流被收集到列表

This groups into a List all consecutive integers where the second one is equal to the next function applied to the first one. Finally, this Stream is collected into a List.

这篇关于分组值序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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