Over a million developers have joined DZone.

Google Guava Goodness: Matching All Elements in a Collection

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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);

 

 

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}