java - Group sequences of values -
i'm wondering if there's in nifty way use new stream apis "group" sequences of values.
e.g. split series of integers, groups of integers each group ascending number sequence:
intstream seq = intstream.of(1, 2, 3, -1, -1, 1, 2, 1, 2); intfunction next = -> + 1; // desired output: [[1,2,3], [-1], [-1], [1,2], [1,2]]
unfortunately, stream api not suited tackle problems involve dependant operations on stream element, one.
however, can use streamex library this:
public static void main(string[] args) { intstream seq = intstream.of(1, 2, 3, -1, -1, 1, 2, 1, 2); intunaryoperator next = -> + 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]]" }
this groups list
consecutive integers second 1 equal next
function applied first one. finally, stream collected list
.
Comments
Post a Comment