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

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

问题描述

Java 8 引入了一个 Stream 类,类似于 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 beenered 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);
}

这将递归地创建一个过滤器,但最终是创建 IntPredicates 树还是创建 IntStreams 树并不重要(就像你的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天全站免登陆