Skip to content

Instantly share code, notes, and snippets.

@dominicfarr
Created February 27, 2012 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominicfarr/1925814 to your computer and use it in GitHub Desktop.
Save dominicfarr/1925814 to your computer and use it in GitHub Desktop.
Chain google collections
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