Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 162 posts at DZone. You can read more from them at their website. View Full User Profile

Google Guava Goodness: Matching All Elements in a Collection

09.20.2012
| 6444 views |
  • submit to reddit

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[a-z]+$");

assert Iterables.all(list, startWithG);

 

 

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Vijay Nathani replied on Fri, 2012/09/21 - 1:02am

Your 2nd example in Groovy can also be written as 

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.List;
def list = ["Google", "Guava"]

assert Iterables.all(list, { it.startsWith("G") } as Predicate ); 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.