Splitter omitEmptyStrings() method | Guava | Java
Last Updated :
31 Jan, 2019
The method omitEmptyStrings() returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results. For example, Splitter.on (‘, ‘).omitEmptyStrings().split(“, a,,, b, c,,”) returns an iterable containing only [“a”, “b”, “c”].
Syntax:
public Splitter omitEmptyStrings()
Return Value: This method returns a splitter with the desired configuration.
Note: If either trimResults option is also specified when creating a splitter, that splitter always trims results first before checking for emptiness. So, for example,
Splitter.on(‘:’).omitEmptyStrings().trimResults().split(“: : : “)
returns an empty iterable.
Below examples illustrate the working of omitEmptyStrings() method:
Example 1:
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
public static void main(String[] args)
{
String str = "geeks,, for,,, geeks,, noida,,, classes" ;
System.out.println( "String with empty strings: \n"
+ str);
List<String> myList = Splitter.on( ', ' ).
trimResults().omitEmptyStrings().splitToList(str);
System.out.println( "\nString with empty"
+ " strings removed: \n"
+ myList);
}
}
|
Output:
String with empty strings:
geeks,, for,,, geeks,, noida,,, classes
String with empty strings removed:
[geeks, for, geeks, noida, classes]
Example 2:
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
public static void main(String[] args)
{
String str = "Hello..$.$ everyone..$& $ what's up..?" ;
System.out.println( "String with empty strings: \n"
+ str);
List<String> myList = Splitter.on( '.' ).
trimResults().omitEmptyStrings().splitToList(str);
System.out.println( "\nString with empty"
+ " strings removed: \n"
+ myList);
}
}
|
Output:
String with empty strings:
Hello..$.$ everyone..$& $ what's up..?
String with empty strings removed:
[Hello, $, $ everyone, $& $ what's up, ?]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...