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
splitwith 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
limitoverload. - Performance in a loop: If splitting the same pattern many times, precompile a
Patternobject and usepattern.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
Patternclass hassplitAsStream(CharSequence)which returns aStreamdirectly, 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
- STRING_SPLIT SQL Server Syntax & Examples
- Software for Data Entry: Top Tools Compared
- Generate Random Numbers on Casio Calculator
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Divide a Cell in Half in Excel: 3 OptionsTo divide a cell in half in Excel, first choose what you mean by “divide”: Excel cannot turn…
- Excel Min Sec Format: Display Minutes and SecondsTo display minutes and seconds in Excel, select the cells, press Ctrl+1, choose Number > Custom, and enter…
- Data Entry How to Do: Steps, Tools, and Accuracy TipsData entry is the process of transcribing, updating, or verifying information into a digital system, and you do…
- Excel Not Responding When Editing a Cell? Causes and FixesIf Excel stops responding while you edit a cell, first wait briefly in case it is calculating or…
- Copy a Word Document into Excel: Best Methods and TipsYes. To copy a Word document into Excel, select the content in Word, press Ctrl+C, click the destination…
- Best Action Button Shortcuts for iPhone 15 Pro & 16The top pick is the Action Button + Shortcuts app combo using a single personal automation that switches…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.