Split String in Java 8: Methods and Examples

How-to basics · Updated November 23, 2026

In Java 8, you split a string using the String.split(String regex) method, which returns a String[] array, or the String.split(String regex, int limit) overload for more control. For example, "a,b,c".split(",") returns {"a", "b", "c"}. Java 8 also introduced String.join() and the Stream API, which let you split and process parts in a functional style, such as Arrays.stream("a,b,c".split(",")).map(String::trim).

Background: Why Split Strings in Java 8?

String splitting is a fundamental operation when parsing CSV files, reading user input, or extracting tokens from log lines. Java 8 (released in 2014) did not add a new split method, but it gave developers the Stream API, which changed how you work with the resulting arrays. Before Java 8, you would split and then loop with a for loop. With Java 8, you can chain operations like filtering, mapping, and collecting directly on the split result, making code more concise and less error-prone.

How String.split Works

The split method treats the argument as a regular expression (regex), not a literal string. This is the most common source of confusion. For instance, "a.b".split(".") returns an empty array because . matches any character. To split on a literal dot, you must escape it: "a.b".split("\\.").

There are two overloads:

  • split(String regex) – splits on every match, discarding trailing empty strings. For example, "a,b,".split(",") returns {"a", "b"} (the trailing empty is removed).
  • split(String regex, int limit) – controls how many times the regex is applied. A negative limit keeps all trailing empty strings; a positive limit limits the number of resulting elements; zero (default) discards trailing empties.

Example with limit:

String s = "one,two,three,four";
String[] parts = s.split(",", 2); // {"one", "two,three,four"}
String[] all = s.split(",", -1); // {"one", "two", "three", "four"}

Using Java 8 Streams for Splitting

Java 8’s Stream API lets you process the split parts without a manual loop. A typical pattern is:

String csv = "apple, banana, cherry";
List<String> fruits = Arrays.stream(csv.split(","))
        .map(String::trim)
        .collect(Collectors.toList());
// Result: ["apple", "banana", "cherry"]

You can also filter out empty strings:

String data = "a,,b,";
List<String> nonEmpty = Arrays.stream(data.split(","))
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toList());
// Result: ["a", "b"]

This is more readable than a traditional loop, especially when you need to transform each part (e.g., parsing integers or trimming whitespace).

Choosing the Right Split Method

Decide based on your needs:

  • Simple delimiter (comma, space, tab): Use split with the literal character, but remember to escape regex metacharacters like ., |, *, +, ?, (, ), [, ], {, }, ^, $, \.
  • Multiple delimiters: Use a regex character class, e.g., split("[;,] ") splits on semicolon, comma, or space.
  • Need to keep trailing empties: Use split(regex, -1).
  • Need to limit parts: Use the limit overload.
  • Performance in a loop: If splitting the same pattern many times, precompile a Pattern object and use pattern.split(input) for better performance.

Common Problems and Misconceptions

One frequent issue is that split discards trailing empty strings by default. If you parse a CSV line that ends with a comma, you might lose the last empty field. Using split(",", -1) solves that.

Another misconception is that split splits on literal characters. Because it uses regex, characters like ., |, and * behave unexpectedly. Always escape them or use Pattern.quote() to treat the delimiter literally:

String literalDot = Pattern.quote(".");
String[] parts = "a.b.c".split(literalDot); // {"a", "b", "c"}

Also, splitting an empty string with a positive limit can return an array with one empty string. For example, "".split(",") returns { "" } in Java 8, which surprises many developers.

Alternatives to String.split

Java 8 offers other ways to break strings:

  • StringTokenizer (legacy) – does not support regex, but is faster for simple delimiters. However, it is discouraged in modern code.
  • Scanner – useful for reading tokens from a stream, but heavier for a single string.
  • Pattern.splitAsStream – Java 8’s Pattern class has splitAsStream(CharSequence) which returns a Stream directly, avoiding the intermediate array. Example:
Pattern comma = Pattern.compile(",");
List<String> list = comma.splitAsStream("a,b,c")
        .collect(Collectors.toList());

This is more memory-efficient for very large strings because it streams the results lazily.

Performance Considerations

If you split in a tight loop, compiling the regex each time is wasteful. Java caches a few patterns, but not all. Best practice is to precompile:

Pattern p = Pattern.compile(",");
for (String line : lines) {
    String[] parts = p.split(line);
    // process
}

For simple single-character delimiters, you can also use String.indexOf and substring in a loop, which is faster but more verbose. In most applications, split is fast enough.

Frequently Asked Questions

How do I split a string on a pipe character in Java?

Pipe (|) is a regex alternation metacharacter, so you must escape it: "a|b|c".split("\\|") or use Pattern.quote("|"). Without escaping, it splits on every empty match, giving an array of single characters.

Why does split return an empty first element when the string starts with the delimiter?

Because the regex engine finds a match at position 0, and the substring before that match is empty. For example, ",a".split(",") returns {"", "a"}. To skip leading empty strings, you can filter them out or use a regex like ^, to remove the first delimiter manually.

Can I split a string into a List directly without an array?

Yes, in Java 8 you can use Arrays.asList(str.split(regex)) or the stream approach: Arrays.stream(str.split(regex)).collect(Collectors.toList()). The latter allows further processing.

What’s the difference between split and StringTokenizer?

String.split uses regex and returns a String[]. StringTokenizer is a legacy class that treats delimiters as literal characters and returns tokens one at a time. It does not support regex and is not recommended for new code because it’s less flexible and has inconsistent behavior with empty tokens.

How do I split a string by newline in Java 8?

Use str.split("\\r?\\n") to handle both Windows (\r\n) and Unix (\n) line endings. Alternatively, Java 8 has String.lines() which returns a Stream of lines, but that was added in Java 11, so in Java 8 you must use split.

Is split thread-safe?

Yes, String.split is thread-safe because String objects are immutable and the method creates a new array each time. However, if you use a shared Pattern object, it is also thread-safe as long as you don’t modify it.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.