Remove Duplicate Objects from a List using Java

In this post, I will show you how to remove duplicate objects from a List using Java’s Comparator interface implementation based on multiple fields in a POJO.

Prerequisites

The following configurations are required in order to run the application

Eclipse
JDK 1.8
Have maven installed and configured
Junit, Mockito, PowerMockito dependency in pom.xml

Now we will see the below steps how to create a maven based Java project in Eclipse Continue reading “Remove Duplicate Objects from a List using Java”

Find Duplicate Objects in a List using Java

In this post, I will show you how to find duplicate objects in a List using Java’s Comparator interface implementation based on multiple fields in a POJO.

Prerequisites

The following configurations are required in order to run the application

Eclipse
JDK 1.8
Have maven installed and configured
Junit, Mockito, PowerMockito dependency in pom.xml

Now we will see the below steps how to create a maven based Java project in Eclipse Continue reading “Find Duplicate Objects in a List using Java”

Comparator interface in Java

For more information please go through http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S. Continue reading “Comparator interface in Java”

Comparable interface in Java

For more information please go through http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

This interface imposes a natural ordering on objects of each class that implements it and the class’s compareTo method is referred to as its natural comparison method.

Lists or arrays of objects that implement this interface can be sorted automatically by Collections.sort or Arrays.sort respectively. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
Continue reading “Comparable interface in Java”