In this post I will show you how to filter and transform ('map' in functional terms) a collection using guava. It's easy to understand and natural if you have experience in functional programming.
I'll start with a simple way to add items to a collection:
... import com.google.common.base.Function; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; ... Iterables.addAll(dest, source);
This method simply adds all elements in source to dest. The signature of the addAll method is:
public static <T> boolean addAll(Collection<T> dest, Iterable<? extends T> source)
In this step I'll filter source:
Iterables.addAll(dest, Iterables.filter(source, Predicates.not(Predicates.containsPattern("\\.")));
I'm asuming that both dest and source are collections of Strings. In the previous line, I'm adding all elements in source that don't contain a ".".
Finally suppose you want to transform the source collection to add a suffix to each element before adding it to dest.
Iterables.addAll(dest, Iterables.transform( Iterables.filter(source, Predicates.not(Predicates.containsPattern("\\."))), new Function < String, String >() { public String apply(String input) { return input + ".xml"; } }));
transform takes two arguments: the source Iterable and a Function that perform the transformation over each element in the source. Here I'm using String as both the type of the elements in the input collection and the elements in the returned collection, but transform can take a collection of some type and the function would return the collection of some other type, for example:
Iterables.addAll(dest, Iterables.transform(otherSource, new Function < Integer, String >() { public String apply(Integer input) { return input.toString(); } }));
That's it. Later I hope to post other uses's examples of this library.
Great Article on Google's guava
ReplyDeleteThank you for such a well written article. It’s full of insightful information and entertaining descriptions. Your point of view is the best among many.
ReplyDeleteembroidery digitizing
Inteeresting thoughts
ReplyDelete