Java - Interface Functional Interfaces

What is Functional Interface?

An interface with just one abstract method is known as a functional interface.

The static and default methods are not counted.

Comparable Interface

A class implements the Comparable interface if objects of the class need to be compared for sorting purposes.

The Comparable interface is a generic interface declared as follows:

public interface Comparable<T> {
        public int compareTo(T o);
}

The String class and wrapper classes ( Integer, Double, Float, etc.) implement the Comparable interface.

The String class's compareTo() method sorts strings lexicographically.

All wrapper classes for the numeric primitive types compare the two objects numerically.

The following class A implements the Comparable<A> interface using A as its generic type.

It states that the class A supports only comparing objects of its own type:

public class A implement Comparable<A> {
        public int compareTo(A a) {
                /* Code goes here */
        }
}

Demo

import java.util.Arrays;

class ComparablePerson implements Comparable<ComparablePerson> {
  private String firstName;
  private String lastName;

  public ComparablePerson(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }/*from   ww w .j a  va 2 s  .  c o  m*/

  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;
  }

  // Compares two persons based on their last names. If last names are
  // the same, use first names
  public int compareTo(ComparablePerson anotherPerson) {
    int diff = getLastName().compareTo(anotherPerson.getLastName());
    if (diff == 0) {
      diff = getFirstName().compareTo(anotherPerson.getFirstName());
    }
    return diff;
  }

  public String toString() {
    return getLastName() + ", " + getFirstName();
  }
}

public class Main {
  public static void main(String[] args) {
    ComparablePerson[] persons = new ComparablePerson[] {
        new ComparablePerson("A", "X"), new ComparablePerson("B", "Y"),
        new ComparablePerson("C", "Z") };

    System.out.println("Before sorting...");
    print(persons);

    // Sort the persons list
    Arrays.sort(persons);

    System.out.println("\nAfter sorting...");
    print(persons);
  }

  public static void print(ComparablePerson[] persons) {
    for (ComparablePerson person : persons) {
      System.out.println(person);
    }
  }
}

Result

Example