How to remove empty values while split in Java:
Suppose a string is given and its words are separated by a separator, including the empty values. We need to write a program to remove the empty values of the string and put the words in an array.
Let’s say the string is:
"one,two,,three,,four,,, ,"
In the above string, there are empty words, and each word is separated by a comma.
Now, let’s try to get the non-empty words in a separate array in different ways:
By using stream:
We can use the split
method to get the words in an array and the stream API can be used to filter out the non-empty words of that array. The program will use the following steps:
- Use the
split
method to get an array of the string words. - Convert that array to a stream with the
Arrays.stream
method. - Remove all empty values of the stream by using the
filter
method. - Convert the stream back to an array by using the
toArray
method.
Below is the complete program:
import java.util.Arrays;
public class Example1 {
public static void main(String[] args) {
String givenString = "one,two,,three,,four,, , ,";
String[] resultArray = Arrays.stream(givenString.split(",")).filter(e -> e.trim().length() > 0)
.toArray(String[]::new);
System.out.println(Arrays.toString(resultArray));
}
}
Download it on Github
If you run the above program, it will give the following result:
[one, two, three, four]
You might also like:
- How to remove specific items or remove all items from a HashSet
- 3 different ways to iterate over a HashSet in Java
- 3 different ways in Java to convert comma-separated strings to an ArrayList
- Java program to convert a character to string
- Java program to convert byte to string
- Java program to convert a string to ArrayList