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").