Created
February 27, 2012 17:45
-
-
Save dominicfarr/1925814 to your computer and use it in GitHub Desktop.
Chain google collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class T | |
{ | |
protected static final Predicate<String> STRING_PREDICATE = new Predicate<String>() | |
{ | |
@Override | |
public boolean apply(final String input) | |
{ | |
return !Strings.isNullOrEmpty(input); | |
} | |
}; | |
protected static final Function<String, String> STRING_FUNCTION = new Function<String, String>() | |
{ | |
@Override | |
public String apply(final String input) | |
{ | |
return input == null ? "" : input.trim(); | |
} | |
}; | |
public static void main(String[] a) | |
{ | |
final List<String> tokens = Lists.newArrayList(" some ", null, "stuff\t", "", " \nhere"); | |
final Collection filtered = transform(tokens, STRING_FUNCTION).thenFilter(STRING_PREDICATE); | |
// Output, as desired: [some, stuff, here] | |
System.out.println(filtered); | |
} | |
private static Then transform(final List<String> tokens, final Function function) | |
{ | |
final Collection transformedCollection = Collections2.transform(tokens, function); | |
return new Then(transformedCollection); | |
} | |
private static class Then | |
{ | |
private Collection collection; | |
public Then(final Collection collection) | |
{ | |
this.collection = collection; | |
} | |
public Collection thenFilter(Predicate predicate) | |
{ | |
return Collections2.filter(collection, predicate); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment