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 */


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   www  .  j a va2 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...");

    // Sort the persons list

    System.out.println("\nAfter sorting...");

  public static void print(ComparablePerson[] persons) {
    for (ComparablePerson person : persons) {