Skip to main content


Showing posts from November, 2011

Guava: String Manipulation with CharMatcher, Spliter and Joiner

Guava has very simple and powerful string manipulation mechanism. Here are some classes like CharMatcher, Splitter and Joiner provides very simple way to perform some complex operation on string collections.

Determines a true or false value for any Java char value, just as Predicate does for any Object.[from guava doc]

Use a predefined constant (predefine CharMatcher)
CharMatcher.WHITESPACE (Java whitespace character)CharMatcher.JAVA_DIGITCharMatcher.JAVA_LETTERCharMatcher.JAVA_LOWER_CASE CharMatcher.JAVA_UPPER_CASE CharMatcher.ASCIICharMatcher.ANY...
String str = "FirstName LastName +1 123 456 789 !@#$%^&*()_+|}{:\"?><"; CharMatcher.DIGIT.retainFrom(str); Output:-> "1123456789" CharMatcher.JAVA_LETTER.retainFrom(str); Output:-> "FirstNameLastName" CharMatcher.JAVA_LETTER_OR_DIGIT.retainFrom(str); Output:-> "FirstNameLastName1123456789" CharMatcher.ANY.countIn(str) Output:-> 54 CharMatcher.DIGIT…

Guava: Function, Predicate and Ordering

Function and Predicate are just interfaces but plays key roll in many use-cases.

Function: Determines an output value based on an input value
Predicate: Determines a true or false value for a given input.
Ordering: It's a comparator with added methods to support common functions.

Assume we have some User Object List
User{firstName=userA, lastName=B, salary=1234567.0} User{firstName=userB, lastName=C, salary=1234577.0} User{firstName=userB, lastName=D, salary=1234777.0} User{firstName=userE, lastName=A, salary=1237777.0} User{firstName=userD, lastName=A, salary=1237778.0} User{firstName=userA, lastName=D, salary=1237788.0}

User Function Class
public enum UserFunctions implements Function<User, String>{ FIRSTNAME{ @Override public String apply(User user){ return user == null ? "" : user.getFirstName(); } }, LASTNAME{ @Override public String apply(User user){ return user == null ? "" : user.getLastName(); } }, FIRSTNAME_LASTNAME{ …