Apache Commons Collections: Object equality using Predicate

The method equals() is the way to check the object equality in Java. You need to override equals() and hashCode() method to makes objects equals. However, in this blog, instead of obj1.equals(obj2) method, I am going to use more powerful Predicate from the Apache commons collection.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.blogspot.ojitha.commonexamples</groupId>
	<artifactId>Apache-common-example</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>Apache-common-example</name>
	<url>http://ojitha.blogspot.com</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>

	</dependencies>
</project>

Here the simple example, In this example, p1 and p2 are instances of Person. Because both carries the same values, objects should be equals.

package com.blogspot.ojitha.commonexamples;

import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.functors.EqualPredicate;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class PredicateExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person p1 = new Person("Ojitha", "Kumanayaka");
		Person p2 = new Person("Ojitha", "Kumanayaka");
		Predicate nameOj = new EqualPredicate(p1);
		System.out.println(nameOj.evaluate(p2));

	}

}

class Person {
	private String firstName;
	private String lastName;
	
	public Person(String first, String last){
		this.firstName = first;
		this.lastName = last;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public int hashCode( ) {    return HashCodeBuilder.reflectionHashCode(this);}
	public boolean equals(Object o) {    return EqualsBuilder.reflectionEquals(this, o);}
	
}

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python