Splitter Class
work opposite to the joiner, Split string into the elements of collection using delimeter which can be sequence of chars,CharMatcher or a regex.
let's see how splitter work using sample code.
Strings Class
lets see how splitter work using the following sample code.
@GwtCompatible(emulated=true) public final class Splitter extends Object
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. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixed length.let's see how splitter work using sample code.
/**
*
*/
package com.rajkrrsingh.test.guava;
import java.util.Iterator;
import com.google.common.base.Splitter;
/**
* @author rks
* @04-Jan-2015
*/
public class GuavaSplitterDemo {
public static void main(String[] args) {
splitterDemo();
}
// Split a string into a collection of elements
public static void splitterDemo(){
Iterator<String> itr = Splitter.on("#").split("RKS#John#Harry#Tom").iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
// split on pattern
Iterator<String> itr1 = Splitter.onPattern("\\d+").split("RKS1John2Harry3Tom").iterator();
while(itr1.hasNext()){
System.out.println(itr1.next());
}
// omit empty string
Iterator<String> itr2 = Splitter.on("#").omitEmptyStrings().trimResults().split("RKS# #John# #Harry#Tom").iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
// fixed length string extractor
Iterator<String> itr3 = Splitter.fixedLength(3).split("RKS#John#Harry#Tom").iterator();
while(itr3.hasNext()){
System.out.println(itr3.next());
}
}
}
Strings Class
@GwtCompatible public final class Strings extends Object
Static utility methods pertaining to
String or CharSequence instances.lets see how splitter work using the following sample code.
/**
*
*/
package com.rajkrrsingh.test.guava;
import com.google.common.base.Strings;
/**
* @author rks
* @04-Jan-2015
*/
public class GuavaStringsDemo {
public static void main(String[] args) {
stringHelper();
}
// helper class to String
public static void stringHelper(){
String str = "";
if(Strings.isNullOrEmpty(str)){
System.out.println("String is null or empty");
}
System.out.println(Strings.nullToEmpty(str));
System.out.println(Strings.emptyToNull(Strings.nullToEmpty(str)));
//repeat a string
System.out.println(Strings.repeat("RKS", 3));
// string padding
System.out.println(Strings.padEnd("RKS", 10, '*'));
System.out.println(Strings.padStart("RKS", 10, '*'));
}
}
No comments:
Post a Comment