Loading...

Friday, September 14, 2012

Google Guava Goodness: Matching All Elements in a Collection

The Google Guava libraries has many useful classes and methods. Normally I write code in Groovy and I am used to working with collections in an intuitive way. But sometimes I need to work with Java on my project and then the Google Guava libraries are a great alternative.

Suppose I want to check if all elements in a collection apply to a certain condition. In Groovy I would write this:

final List<String> list = ['Groovy', 'Rocks']

assert list.every { it.contains('o') }

Now in Java and Google Guava I have the following snippet:

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.List;

final List<String> list = Lists.newArrayList("Google", "Guava");

final Predicate<String> startWithG = new Predicate<String>() {
    @Override
    public boolean apply(final String stringValue) {
        return stringValue.startsWith("G");
    }
};

assert Iterables.all(list, startWithG);

If we use a regular expression pattern we can even simplify the previous code to:

import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.List;

final List<String> list = Lists.newArrayList("Google", "Guava");

final Predicate startWithG = Predicates.containsPattern("^G");

assert Iterables.all(list, startWithG);

(Sample with Google Guava version 13.0.1)

6 comments:

Søren Berg said...

Guava looks nice, but you just gotta love Groovy!

Anonymous said...

You can try with lambdaJ http://code.google.com/p/lambdaj/

but groovy ROCKS!!!!!!!

Ken said...

Your regular expression is not equivalent to the non-RE Guava example; the first will match the string "G" and the second will not. The simpler expression "^G" is equivalent.

And yeah, Groovy rocks!

Hubert Klein Ikkink said...

@Ken thank. I always feel uncomfortable with regular expressions ;). I changed the example and replaced ^G[a-z]+$ with ^G.

Hubert Klein Ikkink said...

@Anonymous: Lambaj looks like a library I want to investigate further. Thank you for the link.

Par said...

This is great. However, with the release of Java 8 (and lambdas), this will no longer be necessary since corresponding functionality will be provided out-of-the-box in the Collections API.

Post a Comment