Java Scanner tokens() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 9+

Definition

In Java, sc.tokens() returns a lazy Stream<String> containing every remaining token produced by the scanner's current delimiter. Requires Java 9 or newer.

It lets you filter, map, count, or collect scanner tokens with Stream pipelines instead of writing a manual while (sc.hasNext()) loop.

An instance method of java.util.Scanner, added in Java 9 (JDK 9). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.tokens(...). Requires Java 9 or newer.

Requires Java 9 or newer.

tokens() was added in Java 9, so these examples do not compile on Java 8. Closing the returned Stream also closes the Scanner, so keep either one inside try-with-resources.

Syntax

Import java.util.stream.Collectors (or Stream) and call sc.tokens() on Java 9+.

Java
Scanner sc = new Scanner("red blue green");
List<String> list = sc.tokens().collect(Collectors.toList());
CallWhat it does
sc.tokens()Returns a lazy Stream<String> of remaining tokens (Java 9+).
sc.tokens().collect(Collectors.toList())Gathers remaining tokens into a List<String>.
sc.tokens().count()Counts remaining tokens while consuming them from the scanner.

Calling terminal stream operations consumes tokens from the scanner. Do not call sc.next() or modify the scanner while a stream pipeline from tokens() is running.

Library declarations
Java
// java.util.Scanner (Java 9+)
public Stream<String> tokens()

Parameters

ParameterDescription
Nonetokens() takes no parameters.

Return Value

Return ValueDescription
Stream<String>A lazy sequential stream of the remaining delimiter-separated tokens.
Throws IllegalStateExceptionIf the scanner has already been closed when the stream executes.

Compare with Similar Methods

Streaming tokens vs loops and files:

MethodHow it differs
hasNext() / next()Classic Java 5+ loop alternative.
useDelimiter(p)Controls what tokens tokens() yields.
Files.lines(path)Streams whole lines from a file Path (Java 8+).

Java Examples

Example 1 — Skip a Header Word, Then Collect Remaining Tokens into a List

Consume the label with next() first, then stream only the remaining tokens with tokens() (Java 9+).

Java
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class ScannerTokensCollect {
    public static void main(String[] args) {
        String input = "Tags: java scanner streams parsing";
        try (Scanner sc = new Scanner(input)) {
            String header = sc.next();
            List<String> tags = sc.tokens().collect(Collectors.toList());
            System.out.println("Header: " + header);
            System.out.println("Remaining: " + tags);
        }
    }
}

How It Works

  1. Stream starts from current cursor. Because sc.next() already consumed "Tags:", tokens() yields only the four tags.
  2. Java 9 stream, Java 8 collector. Collectors.toList() works cleanly on Java 9+ without needing Java 16's toList().
  3. Scanner closed via try-with-resources. Even though the stream finishes, try (...) ensures sc.close() still runs.

Example 2 — Filter and Uppercase CSV Tokens Using Stream Operations

Combine useDelimiter("\\s*,\\s*") with tokens() to normalize and filter tags (Java 9+).

Java
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class ScannerTokensFilter {
    public static void main(String[] args) {
        String csv = "ada,  , bob , cy , anna";
        try (Scanner sc = new Scanner(csv).useDelimiter("\\s*,\\s*")) {
            List<String> names = sc.tokens()
                .filter(s -> s.length() >= 3)
                .map(String::toUpperCase)
                .collect(Collectors.toList());
            System.out.println("Filtered names: " + names);
        }
    }
}

How It Works

  1. Custom delimiter respected. tokens() yields tokens split by \\s*,\\s*, including the empty middle token "".
  2. Stream filters blanks and short words. Keeping length() >= 3 removes both "" and "cy".
  3. Method reference uppercase. String::toUpperCase transforms the remaining three names cleanly.

Example 3 — See That Closing the Stream Also Closes the Scanner

Count the tokens inside try-with-resources, then show that the scanner is closed afterwards and throws IllegalStateException (Java 9+).

Java
import java.util.Scanner;
import java.util.stream.Stream;

public class ScannerTokensState {
    public static void main(String[] args) {
        Scanner sc = new Scanner("one two");
        try (Stream<String> st = sc.tokens()) {
            System.out.println("Counted: " + st.count());
        }
        try {
            sc.hasNext();
        } catch (IllegalStateException e) {
            System.out.println("hasNext() after stream closed: " + e.getClass().getSimpleName());
        }
        try {
            sc.tokens();
        } catch (IllegalStateException e) {
            System.out.println("tokens() on closed scanner: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Closing the stream closes the scanner. When the try (Stream) block ends, the stream's close handler calls sc.close() for you.
  2. Tokens consumed by count(). The terminal count() operation reads both tokens, so it prints Counted: 2.
  3. A closed scanner rejects everything. Both sc.hasNext() and sc.tokens() now throw IllegalStateException.

Frequently Asked Questions

Java 9. It is not available on Java 8 or earlier.
Yes. The stream registers the scanner's close() as its close handler, so closing the stream closes the scanner. Using try-with-resources on either one is enough.
No. Calling other Scanner methods while a tokens() stream terminal operation is running produces unpredictable results.
Yes. It splits tokens using whatever delimiter is active on the scanner.
No. It streams only the tokens remaining from the scanner current position forward.

Next: useDelimiter()

Change the delimiter Pattern used to separate tokens.

useDelimiter() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful