0

We have a long string with numbers or words separated by space. We need to get stream of them. What is a preferred method?

I know two options:

  1. Arrays(str.split(“ “)).stream();
  2. new Scanner(str).tokens();

Both return a stream of strings. Which option is better?

Any other methods?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Jegors Čemisovs
  • 608
  • 6
  • 14
  • 2
    I'd go with the stream. I wouldn't want to open a new Scanner. – Paul Jul 06 '20 at 07:36
  • 1
    In the reference implementation, the `Scanner(String)` constructor does not utilize the fact that this is already an in-memory `String`, but creates a `StringReader`, following the same logic as reading from an external source. In other words, it’s horribly inefficient. Beyond this new, discouraged option, it’s the same question as [How to split a String into a Stream of Strings?](https://stackoverflow.com/q/40932813/2711488) – Holger Jul 07 '20 at 12:29

1 Answers1

1

Both are valid, but not sure about the performance. Another option is to use StringTokenizer:

Collections.list(new StringTokenizer(str)).stream()

It provides more ways to customize the tokens.

Edit: no need to pass the white space delimiter since it's the default.

Marc
  • 2,738
  • 1
  • 17
  • 21
  • I know about StringTokinizer but never use it. Is it still actual? It come from Java 1.0. Anyway thanks for one more method! – Jegors Čemisovs Jul 06 '20 at 07:57
  • 2
    [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) clearly states: _`StringTokenizer` is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the `split` method of `String` or the `java.util.regex` package instead._ – Nowhere Man Jul 06 '20 at 08:03
  • Thanks @AlexRudenko for the heads up, I will update your comment. – Marc Jul 06 '20 at 08:11