Almost exactly four years ago, Cay Horstmann was complaining that it wasn't possible to get a Stream out of a Scanner. Even confirmed Scannerophobes like Winston thought that should be possible. In the Horstmann blog, somebody called Rémi said maybe Java9 would introduce a way to get a Stream from a Scanner. So I had a look about 4.00 o'clock today, and lo and behold, there are two/three methods: findAll() (overloaded) and tokens(). So I thought I would try them out:
Enter tokens: 0 to finish: Coderanch 1 2 69 is brilliant 4 ldhdl 123.45 0
Enter more tokens: 0 to finish: Coderanch 1 2 69 is brilliant 4 ldhdl 123.45 0
1+2+69+4=76; in the first case it was perceiving the 123 and the 45 as matching the regex supplied: 1+2+69+4+123+45=244.
If you don't have some means of stopping the Stream, it may turn into an infinite Stream.
There isn't a lines() method, but it should be easy enough to get lines from tokens() with something like
useDelimiter("\r|\n|\r\n") or useDelimiter(System.lineSeparator())
I am sure people will be q‑U‑E‑U‑E‑I‑n‑g up to try that bit of code. I shall try it myself in a minute.
posted 1 year ago
Why does Louie appear twice? I see there aren't any words with five consecutive vowels, not even q‑U‑E‑U‑E‑I‑n‑g. I can see the logic of creating a Stream<String> from tokens() because, as Winston said in the other old thread, a Scanner IS‑AN Iterator<String>, and what you get from its next() method implemented from Iterator is a token, so the Stream supplies the same as you get from the method from Iterator.
I see there is a hasNext() method, but the remove
operation is not supported by this implementation of Iterator.
Obviously Iterator#remove() will be called an optional operation. It always struck me as peculiar that you can have interfaces with optional operations, but I suppose that is how you get Lists where you can add elements and Lists where you can't add elements.
I resemble that remark!
Hi all. Long time no Ranchee. Though I'd pop back to find some pearls of wisdom about Java 9, since I've just acquired a new laptop for a steal (150 quid for a 5-year old i5 HP, with 8 gig and and a fingerprint scanner) and want to install it.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here