Home > Programming / tutorials > How to Use Predicate

How to Use Predicate

November 15th, 2014 Leave a comment Go to comments

Predicate

Predicate is interface from google guava which determines a true or false value for a given input.

How do you use Predicate ? Below is an example on how you can use predicate to findĀ element from collection based on Id . It is assumed that the object which is a subclass or of type IDObject.


import java.util.Collection;
import java.util.Set;
import com.google.common.base.Predicate;

public class FindByIdPredicate implements
		Predicate<IDObject> {

	private Long entityId;

	public FindByIdPredicate(final Long entityId) {
		this.entityId = entityId;

	}

	@Override
	public boolean apply(final IDObject input) {
		return input.getId().equals(this.entityId);
	}

	/**
	 * @param Collection
	 * @return IdObject if present or null
	 */
	public IDObject getEntity(final Collection<? extends IDObject> collection) {

		for (IDObject idObject : collection) {
			if (this.apply(idObject)) {
				return idObject;
			}
		}
		return null;

	}

	/**
	 * @param Set
	 * @return IdObject if present or null
	 */
	@SuppressWarnings("unchecked")
	public <T> T getEntity(final Set<? extends IDObject> set) {

		for (IDObject idObject : set) {
			if (this.apply(idObject)) {
				return (T) idObject;
			}
		}
		return null;

	}
}

As you can see , it makes is super easy and quick to find an object from collection using predicate which other wise you would have to iteration and check for each object