Java 8 Stream,得到头和尾Java、Stream

2023-09-07 01:00:59 作者:学霸的芯

Java 8 引入了一个类似于 Scala 的 Stream,一个强大的惰性结构可以非常简洁地做这样的事情:

Java 8 introduced a Stream class that resembles Scala's Stream, a powerful lazy construct using which it is possible to do something like this very concisely:

def from(n: Int): Stream[Int] = n #:: from(n+1)

def sieve(s: Stream[Int]): Stream[Int] = {
  s.head #:: sieve(s.tail filter (_ % s.head != 0))
}

val primes = sieve(from(2))

primes takeWhile(_ < 1000) print  // prints all primes less than 1000

我想知道在 Java 8 中是否可以做到这一点,所以我写了这样的东西:

I wondered if it is possible to do this in Java 8, so I wrote something like this:

IntStream from(int n) {
    return IntStream.iterate(n, m -> m + 1);
}

IntStream sieve(IntStream s) {
    int head = s.findFirst().getAsInt();
    return IntStream.concat(IntStream.of(head), sieve(s.skip(1).filter(n -> n % head != 0)));
}

IntStream primes = sieve(from(2));

相当简单,但它会产生 java.lang.IllegalStateException: stream has already been operating on or closed 因为 findFirst()skip()Stream 上的终端操作,只能执行一次.

Fairly simple, but it produces java.lang.IllegalStateException: stream has already been operated upon or closed because both findFirst() and skip() are terminal operations on Stream which can be done only once.

我真的不需要用完两次流,因为我只需要流中的第一个数字,其余的作为另一个流,即等效于 Scala 的 Stream.headStream.tail.我可以使用 Java 8 Stream 中的方法来实现此目的吗?

I don't really have to use up the stream twice since all I need is the first number in the stream and the rest as another stream, i.e. equivalent of Scala's Stream.head and Stream.tail. Is there a method in Java 8 Stream that I can use to achieve this?

谢谢.

推荐答案

即使你没有无法拆分 IntStream 的问题,你的代码也没有工作,因为你是递归调用您的 sieve 方法,而不是延迟调用.因此,在查询结果流以获取第一个值之前,您有一个无限递归.

Even if you hadn’t the problem that you can’t split an IntStream, you code didn’t work because you are invoking your sieve method recursively instead of lazily. So you had an infinity recursion before you could query your resulting stream for the first value.

可以将 IntStream s 分成头部和尾部 IntStream(尚未消费):

Splitting an IntStream s into a head and a tail IntStream (which has not yet consumed) is possible:

PrimitiveIterator.OfInt it = s.iterator();
int head = it.nextInt();
IntStream tail = IntStream.generate(it::next).filter(i -> i % head != 0);

在这个地方,你需要一个懒惰地在尾部调用 sieve 的构造.Stream 不提供;concat 期望现有的流实例作为参数,并且您不能使用 lambda 表达式构造一个调用 sieve 的流,因为延迟创建仅适用于 lambda 表达式不支持的可变状态.如果您没有隐藏可变状态的库实现,则必须使用可变对象.但是一旦你接受了可变状态的要求,解决方案可能比你的第一种方法更容易:

At this place you need a construct of invoking sieve on the tail lazily. Stream does not provide that; concat expects existing stream instances as arguments and you can’t construct a stream invoking sieve lazily with a lambda expression as lazy creation works with mutable state only which lambda expressions do not support. If you don’t have a library implementation hiding the mutable state you have to use a mutable object. But once you accept the requirement of mutable state, the solution can be even easier than your first approach:

IntStream primes = from(2).filter(i -> p.test(i)).peek(i -> p = p.and(v -> v % i != 0));

IntPredicate p = x -> true;

IntStream from(int n)
{
  return IntStream.iterate(n, m -> m + 1);
}

这将递归地创建一个过滤器,但最终无论您是创建 IntPredicate 的树还是 IntStream 的树(就像您的IntStream.concat 方法(如果它确实有效).如果您不喜欢过滤器的可变实例字段,您可以将其隐藏在内部类中(但不能隐藏在 lambda 表达式中……).

This will recursively create a filter but in the end it doesn’t matter whether you create a tree of IntPredicates or a tree of IntStreams (like with your IntStream.concat approach if it did work). If you don’t like the mutable instance field for the filter you can hide it in an inner class (but not in a lambda expression…).