Java 8 Stream,获得头尾 [英] Java 8 Stream, getting head and tail

查看:131
本文介绍了Java 8 Stream,获得头尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8引入了一个类似于Scala的 Stream 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已经已被操作或关闭因为 findFirst() skip()是终端操作在上只能执行一次。

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.head Stream.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);

在这个地方你需要一个调用筛子的构造在懒惰的尾巴上。 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…).

这篇关于Java 8 Stream,获得头尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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