The Wayback Machine - https://web.archive.org/web/20241129031933/https://www.geeksforgeeks.org/comparable-interface-in-java-with-examples/
Open In App

Comparable Interface in Java with Examples

Last Updated : 24 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo method that takes a parameter of the object of that class. In this article, we will see how we can sort an array of pairs of different data types on the different parameters of comparison.

Using Comparable Interface

  • In this method, we are going to implement the Comparable interface from java.lang Package in the Pair class.
  • The Comparable interface contains the method compareTo to decide the order of the elements.
  • Override the compareTo method in the Pair class.
  • Create an array of Pairs and populate the array.
  • Use the Arrays.sort() function to sort the array.

Example 1

Given an array of Pairs consisting of two fields of type string and integer. you have to sort the array in ascending Lexicographical order and if two strings are the same sort it based on their integer value.

Sample I/O:

Input:  { {"abc", 3}, {"a", 4}, {"bc", 5}, {"a", 2} }
Output:  { {"a", 2}, {"a", 4}, {"abc", 3}, {"bc", 5} }

Input:  { {"efg", 1}, {"gfg", 1}, {"cba", 1}, {"zaa", 1} }
Output:  { {"cba", 1}, {"efg", 1}, {"gfg", 1}, {"zaa", 1} }

Java




import java.io.*;
import java.util.*;
 
class Pair implements Comparable<Pair> {
    String x;
    int y;
 
    public Pair(String x, int y)
    {
        this.x = x;
        this.y = y;
    }
 
    public String toString()
    {
        return "(" + x + "," + y + ")";
    }
 
    @Override public int compareTo(Pair a)
    {
        // if the string are not equal
        if (this.x.compareTo(a.x) != 0) {
            return this.x.compareTo(a.x);
        }
        else {
            // we compare int values
            // if the strings are equal
            return this.y - a.y;
        }
    }
}
 
public class GFG {
    public static void main(String[] args)
    {
 
        int n = 4;
        Pair arr[] = new Pair[n];
 
        arr[0] = new Pair("abc", 3);
        arr[1] = new Pair("a", 4);
        arr[2] = new Pair("bc", 5);
        arr[3] = new Pair("a", 2);
 
        // Sorting the array
        Arrays.sort(arr);
 
        // printing the
        // Pair array
        print(arr);
    }
 
    public static void print(Pair[] arr)
    {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}


Output:

Before Sorting:
(abc, 3);
(a, 4);
(bc, 5);
(a, 2);

After Sorting:
(a,2)
(a,4)
(abc,3)
(bc,5)

Note: if two strings are the same then the comparison is done based on the value.

Example 2

Given an array of Pairs consisting of two strings with first and last names. you have to sort the array in ascending Lexicographical order of the first name and if two strings are the same sort it based on their last name.

Sample I/O:

Input:  { {"raj", "kashup"}, {"rahul", "singh"}, {"reshmi", "dubey"}, {"rahul", "jetli"} }
Output:  { {"rahul", "jetli"}, {"rahul", "singh"}, {"raj", "kashup"}, {"reshmi", "dubey"} }

Input:  { {"abc", "last"}, {"pklz", "yelp"}, {"rpng", "note"}, {"ppza", "xyz"} }
Output:  { {"abc", "last"}, {"pklz", "yelp"}, {"ppza", "xyz"}, {"rpng", "note"} }

Java




import java.io.*;
import java.util.*;
 
class Pair implements Comparable<Pair> {
    String firstName;
    String lastName;
 
    public Pair(String x, String y)
    {
        this.firstName = x;
        this.lastName = y;
    }
 
    public String toString()
    {
        return "( " + firstName + " , " + lastName + " )";
    }
 
    @Override public int compareTo(Pair a)
    {
        // if the string are not equal
        if (this.firstName.compareTo(a.firstName) != 0) {
            return this.firstName.compareTo(a.firstName);
        }
        else {
            // we compare lastName if firstNames are equal
            return this.lastName.compareTo(a.lastName);
        }
    }
}
 
public class GFG {
    public static void main(String[] args)
    {
 
        int n = 4;
        Pair arr[] = new Pair[n];
        arr[0] = new Pair("raj", "kashup");
        arr[1] = new Pair("rahul", "singh");
        arr[2] = new Pair("reshmi", "dubey");
        arr[3] = new Pair("rahul", "jetli");
 
        // Sorting the array
        Arrays.sort(arr);
 
        // printing the
        // Pair array
        print(arr);
    }
 
    public static void print(Pair[] arr)
    {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}


Output:

Before Sorting:
( raj , kashup )
( rahul , singh )
( reshmi , dubey )
( rahul , jetli )


After Sorting:
( rahul , jetli )
( rahul , singh )
( raj , kashup )
( reshmi , dubey )

In this article, we sorted user-defined pairs with different data types by using java comparable. 



Previous Article
Next Article

Similar Reads

Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some reasons why you might want to use the Comparator i
9 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
Comparable vs Comparator in Java
Java provides two interfaces to sort objects using data members of the class: ComparableComparatorUsing Comparable Interface A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name,
6 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate<T, V> interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate<T, V> Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
ToLongFunction Interface in Java with Examples
The ToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a long-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input
1 min read
LongToIntFunction Interface in Java with Examples
The LongToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a long-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to define its
1 min read
ToIntFunction Interface in Java with Examples
The ToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces an int-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input a
1 min read
ToDoubleFunction Interface in Java with Examples
The ToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a double-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the in
1 min read
IntFunction Interface in Java with Examples
The IntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
LongFunction Interface in Java with Examples
The LongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a long-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
Supplier Interface in Java with Examples
The Supplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a value of type T. Hence this functional interface takes in only one generic namely:- T: denotes the type of the result The
1 min read
IntConsumer Interface in Java with Examples
The IntConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one int-valued argument but does not return any value. The lambda expression assigned to an object of IntConsumer type is used to define its accept() which
3 min read
LongConsumer Interface in Java with Examples
The LongConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one long-valued argument but does not return any value. The lambda expression assigned to an object of LongConsumer type is used to define its accept() wh
3 min read
Java 8 | LongSupplier Interface with Examples
The LongSupplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a long value. The lambda expression assigned to an object of LongSupplier type is used to define its getAsLong() which e
1 min read
Java 8 | IntSupplier Interface with Examples
The IntSupplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take any argument but produces an int value. The lambda expression assigned to an object of IntSupplier type is used to define its getAsInt() which eventua
1 min read
Java 8 | BooleanSupplier Interface with Examples
The BooleanSupplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a boolean value. The lambda expression assigned to an object of BooleanSupplier type is used to define its getAsBoole
1 min read
Java 8 | DoubleSupplier Interface with Examples
The DoubleSupplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a double value. The lambda expression assigned to an object of DoubleSupplier type is used to define its getAsDouble()
1 min read
Java.util.function.DoubleBinaryOperator interface with Examples
The DoubleBinaryOperator interface was introduced in Java 8. It represents an operation on two double values and returns the result as a double value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods: applyAsDouble(
2 min read
Java.util.function.LongBinaryOperator interface with Examples
The LongBinaryOperator interface was introduced in Java 8. It represents an operation on two long values and returns the result as a long value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods: applyAsLong(): This
1 min read
Java.util.function.IntBinaryOperator interface with Examples
The IntBinaryOperator interface was introduced in Java 8. It represents an operation on two int values and returns the result as an int value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods applyAsInt(): This func
2 min read
Java.util.concurrent.Executor interface with Examples
The concurrent API in Java provides a feature known as an executor that initiates and controls the execution of threads. As such, an executor offers an alternative to managing threads using the thread class. At the core of an executor is the Executor interface. It refers to the objects that execute submitted Runnable tasks. Class hierarchy: java.ut
1 min read
Java.util.concurrent.ExecutorService Interface with Examples
The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status. The ExecutorService interface is implemented in a utility class c
3 min read
ThreadFactory Interface in Java with Examples
The ThreadFactory interface defined in the java.util.concurrent package is based on the factory design pattern. As its name suggests, it is used to create new threads on demand. Threads can be created in two ways: 1. Creating a class that extends the Thread class and then creating its objects. Java Code import java.io.*; class GFG { public static v
7 min read
Collection Interface in Java with Examples
The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. For Example, th
8 min read
SortedMap Interface in Java with Examples
SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap. The SortedMap interface is a subinterface of the java.util.Map interface in Java. It extends the Map i
11 min read
three90RightbarBannerImg