• Post Reply Bookmark Topic Watch Topic
  • New Topic

Detecting an infinite Stream  RSS feed

 
Johnathan Davis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I've now moved on to chapter 2 question 7 in the book "Java 8 for the really impatient". This question asks the reader to implement a method called isFinite which takes a stream as a parameter and returns true if the stream is finite and false otherwise. So far, I have two streams (a finite and an infinite stream):



I'm now trying to find some way to detect which stream is finite and which one is infinite. My first attempt was to try to collect the last element in the stream:



For the finite stream, it does successfully grab the last element in the list, but for the infinite stream, my program crashes and never terminates. I also tried stream.count() and it failed for the infinite stream. I could try to use iterate or forEach, but I don't know how I would know when I saw the last element. Any hints about how I should approach this problem? I looked through the Stream API and didn't see anything particularly helpful. Thanks again.

Note - the book does admit that writing such a method is not a good idea, but they do imply that it is possible (when they say - "go ahead and write it anyways").
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 36446
454
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it is possible. I took that question to mean "go try it and see that it hangs/runs infinitely"
 
Simon Roberts
Author
Ranch Hand
Posts: 176
9
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Best option I know for this is to grab the spliterator from the stream and ask it for the size estimate:



Generates:



But, notice that method is called "estimate size"
 
Stephan van Hulst
Saloon Keeper
Posts: 6981
110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just keep in mind that you can't use the stream after estimating the size this way, because grabbing the spliterator is a terminal operation. If you want to perform a stream operation after estimating the size, you'll have to use StreamSupport.stream() to create a new stream from the spliterator.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!