Introduction
Splitting a string by a delimiter is a fundamental operation in text processing and data manipulation. Whether you’re parsing CSV files, processing user input, or handling any structured data format, being able to split a string into its constituent parts is essential. Java provides a straightforward way to do this using the split() method, but with Java 8, you can achieve this more elegantly using Streams. In this guide, we’ll explore how to create a Java program that splits a string by a delimiter using Java 8 Streams.
Problem Statement
The task is to create a Java program that:
- Accepts a string and a delimiter as input.
- Uses Java 8 Streams to split the string by the specified delimiter.
- Outputs each part of the split string.
Example 1:
- Input:
"apple,banana,orange","," - Output:
["apple", "banana", "orange"]
Example 2:
- Input:
"Java|Python|C++|JavaScript","|" - Output:
["Java", "Python", "C++", "JavaScript"]
Solution Steps
- Input String and Delimiter: Start with a string and a delimiter that can either be hardcoded or provided by the user.
- Split the String: Use the
split()method to break the string into parts based on the specified delimiter. - Stream Processing: Convert the array of split parts into a stream to allow further processing or direct output.
- Display the Result: Print each part of the split string.
Java Program
Java 8 Program to Split a String by Delimiter
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8 Program to Split a String by Delimiter
* Author: https://www.rameshfadatare.com/
*/
public class SplitStringByDelimiter {
public static void main(String[] args) {
// Step 1: Take input string and delimiter
String input = "apple,banana,orange";
String delimiter = ",";
// Step 2: Split the string using streams
List<String> result = splitStringByDelimiter(input, delimiter);
// Step 3: Display the result
result.forEach(System.out::println);
}
// Method to split a string by a given delimiter
public static List<String> splitStringByDelimiter(String input, String delimiter) {
return Arrays.stream(input.split(delimiter))
.collect(Collectors.toList());
}
}
Explanation of the Program
-
Input Handling: The program uses the string
"apple,banana,orange"and the delimiter","as an example input. This can be modified to accept input from the user if required. -
Splitting the String: The
split(delimiter)method is used to break the string into an array of substrings based on the provided delimiter. -
Stream Processing: The
stream()method converts the array into a stream, which is then collected into a list usingCollectors.toList(). This allows for further processing or direct output as needed. -
Output: The program prints each element of the list on a new line.
Output Example
Example 1:
Input: apple,banana,orange
Output:
apple
banana
orange
Example 2:
Input: Java|Python|C++|JavaScript
Output:
Java
Python
C++
JavaScript
Advanced Considerations
-
Multiple Delimiters: If you need to split the string using multiple delimiters, you can modify the
split()method by using a regular expression. For example,split("[,|]")would split on both commas and vertical bars. -
Handling Empty Strings: The program handles empty strings by returning an empty list. If the string is empty or does not contain the delimiter, the resulting list will contain the original string or be empty, depending on the situation.
-
Trimming Whitespace: If the substrings may contain leading or trailing whitespace, you can add a
map(String::trim)step in the stream processing to clean up the parts.
Conclusion
This Java 8 program efficiently splits a string by a specified delimiter using streams. By taking advantage of the Stream API, the solution is both concise and powerful, making it suitable for various text processing tasks. Whether you’re parsing data, handling user input, or working with structured formats, this method provides a flexible and effective approach to splitting strings in Java.