Splitter Class | Guava | Java

Guava’s Splitter Class provides various methods to handle splitting operations on string, objects, etc. It extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed string, regular expression or CharMatcher instance.

Declaration: Following is the declaration for com.google.common.base.Splitter class:

@GwtCompatible(emulated = true)
public final class Splitter
   extends Object

The following table gives a brief summary about the methods of Guava’s Splitter class:

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show implementation of
// Guava's Splitter class's method
  
import com.google.common.base.Splitter;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Splitter.on(char separator) returns a splitter
        // that uses the given single-character separator.
           
        // Splitter omitEmptyStrings() omits empty 
        // strings from the results.
        System.out.println(Splitter.on(',')
                  .trimResults()
                  .omitEmptyStrings()
                  .split("GeeksforGeeks ,is, the, 
                     best, website, to, prepare, for, interviews"));
    }
}

chevron_right


Output:

[GeeksforGeeks, is, the, best, website, to, prepare, for, interviews]

Some other methods provided by the Splitter class are:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show implementation of
// Guava's Splitter class's method
  
import com.google.common.base.Splitter;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // A string variable named str
        String str= "Hello, GFG, What's up ?";
           
        // SplitToList returns a List of the strings. 
        // This can be transformed to an ArrayList or 
        // used directly in a loop.
        List<String> myList = Splitter.on(',').splitToList(str);
           
        for (String ele : myList) {
            System.out.println(ele);
        }
    }
}

chevron_right


Output:

Hello
 GFG
 What's up ?

Reference: Google Guava



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.