How will you compare two java objects

Carvia Tech | May 06, 2019 | 3 min read | 19 views


Java provides two mechanisms to compare objects:

  1. Using Comparable interface

  2. Using Comparator interface

The purpose for using one of these interface depends upon the usecase. We will discuss both the approaches one by one.

Using Comparable Interface

When we implement comparable interface in a class, it imposes a total ordering on its objects. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

Following is the definition for this interface.

Comparable.java
public interface Comparable<T> {

    public int compareTo(T o);

}

Few important points:

  1. Lists of objects that implement this interface can be sorted automatically by Collections.sort or Arrays.sort

  2. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without need to specify a comparator.

Example

Person class with Natural ordering based on name
class Person implements Comparable<Person>{
    int age;
    String name;
    String email;

    @Override
    public int compareTo(Person o) {
        return name.compareTo(o.getName());
    }
}

Now we can sort a collection of persons based on its natural ordering using Collections.sort method.

Sorting in Natural Order
List<Person> students = Arrays.asList(
        new Person(20,"Bob", "bob@mail.com"),
        new Person(19, "Jane", "Jane@mail.com"),
        new Person(21,"Foo", "foo@mail.com")
);
Collections.sort(students);
Program output (sorting based on person’s name)
Bob
Foo
Jane

Using Comparator Interface

A comparison function, which imposes a total ordering on some collection of objects.

Comparator.java
@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

}
  1. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. We can have more than one Comparator for a given class, for example Person class may have two different comparators, one that sorts based on name and another based on age.

  2. 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.

Example

Lets define two comparators now, one for name based comparison and another on basis of age.

NameComparator & AgeComparator
class NameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.name.compareTo(o2.name);
    }
}

class AgeComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return ((Integer)o1.age).compareTo(o2.age);
    }
}

Now we can specify one of the above defined sorting function to choose sorting on demand:

Soritng based on Age
List<Person> students = Arrays.asList(
        new Person(20,"Bob"),
        new Person(19, "Jane"),
        new Person(21,"Foo")
);
Collections.sort(students, new AgeComparator());

Similarly, we can sort based on NameComparator as well.

Java 8 style comparator using lambda approach

Java 8’s lambda can be used to write inline comparator and even chain them as and when required.

Comparing by name and then age (if name is same)
List<Person> students = Arrays.asList(
        new Person(20,"Foo"),
        new Person(19, "Jane"),
        new Person(21,"Foo")
);
Collections.sort(students);
students.stream()
        .sorted(Comparator
                .comparing(Person::getName)
                .thenComparing(Person::getAge)
        ).forEach(System.out::println);

That’s all for this article.


Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. Java program to check if two strings are anagrams
  3. How to reverse a number in Java
  4. How to check if the given number is palindrome in Java
  5. Find two numbers of which the product is maximum in an array
  6. Calculate Fibonacci Series in Java
  7. Check whether given number is even or odd



Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info