Sunday, January 4, 2015

Google Gauva API in a one glance: CharMatcher

It's a class similar to Predicate,apply a boolean check on the chars, have methods to work on the char sequence e.g.
removeFrom(), replaceFrom(), trimFrom(), collapseFrom(), retainFrom()
lets see a simple example involving CharMatcher, follow along the code here
/**
*
*/
package com.rajkrrsingh.test.guava;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;

/**
* @author rks
* @04-Jan-2015
*/
public class GuavaCharMatcherDemo {

public static void main(String[] args) {
charMatcher();
}


public static void charMatcher(){
// remove char occurance in the range of 1 and 4
System.out.println(CharMatcher.inRange('1', '4').removeFrom(" 981 654 239"));
// negate the result obtained from previous statement
System.out.println(CharMatcher.inRange('1', '4').negate().removeFrom(" 981 654 239"));
// count no of digit in the string
System.out.println(CharMatcher.DIGIT.countIn(" 981 654 239 "));
// collapse a matching digits with the provided chars
System.out.println(CharMatcher.DIGIT.collapseFrom("collapse from 981 654 239", 'X'));
// replace digit in the string with the provide char
System.out.println(CharMatcher.DIGIT.replaceFrom("collapse from 981 654 239", 'X'));
// trim a string on matching char
System.out.println(CharMatcher.is(' ').trimFrom(" 981 654 239 "));
System.out.println(CharMatcher.is(' ').trimLeadingFrom(" 981 654 239 "));
System.out.println(CharMatcher.is(' ').trimTrailingFrom(" 981 654 239 "));
System.out.println(CharMatcher.is(' ').trimAndCollapseFrom(" 981 654 239 ",'X'));
}
}
Output
 98 65 9
1423
9
collapse from  X X X
collapse from  XXX XXX XXX
981 654 239
981 654 239 
 981 654 239
981X654X239
please follow the comment in the code to relate output.
Post a Comment