Interface Introduction

Introduce some interface usage in Java. (This is not a comprehensive tutorial!)

What is

An interface is an abstract type that contains a collection of related methods with empty bodies and constant variables. It is one of the core concepts in Java.

Animal.java
// a self-defined interface
interface Animal {
  public void eat(); // interface method (does not have a body)
  public void moving(); // interface method (does not have a body)
  
  
  public static void main(String[] args) {
        //Animal cat = new Animal(); This is wrong
    }
}

An interface can not be used for instantiating an object. It has to be implemented by a class type first.

For example,

hello.sh

public class Cat implements Animal{
    @Override
    public void eat() {
        System.out.println("Cat eats cat food!");
    }

    @Override
    public void moving() {
        System.out.println("Cat jumps, runs and walking!");
    }

    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();
        cat.moving();
    }
}

Functional Interface

A functional interface is any inteface with a single abstract method. For example, the Animal inteface is not a functional interface, but the PPrin.

PPrint.java
// a functional 
public interface PPrint {
    public void print(String msg);
}

Lambdas in Java 8

Llambda expressions are introduced in Java 8.

An expression in Java is an implementation of a functional interface.

A Lambda expression is an expression that should reside in a code body.

Syntax:

(parameter1, parameter2) -> expression
PPrint.java
public interface PPrint {
    public void print(String msg);

    public static void main(String[] args) {
        PPrint banner_print = msg ->
                System.out.println("====================\n" 
                + msg + "\n====================\n");
        banner_print.print("Hello World!");
        
        //without the lambda expression to impplement an interface in line
        // or to write a separate implementation
        PPrint banner_print1 = new PPrint() {
            @Override
            public void print(String msg) {
                System.out.println("====================\n"
                        + msg + "\n====================\n");
            }
        };
        banner_print1.print("Hello World!");        
    }
}

Comparator Functional Interface

Demo.java

public class Demo {
    public static void main(String[] args) {
    /*
    * A comparator interface is used to order the objects of user-defined classes.
    * A comparator object is capable of comparing two objects of two different classes.
    *
    * Using interfacedemo.lambda expression to instantiate an interface
    *
    * And a interfacedemo.lambda expression can only implements an interface with a single abstract method
    *
    *
    * */
        Comparator<String> stringComparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        };
        stringComparator.compare("AB", "CD");
        Comparator<String> stringComparatorLambda = (String o1, String o2) -> o1.compareTo(o2);
    }
}

FrequencySort

FrequencySort.java

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class FrequencySort {
    /**
     * @param arr Comparable array
     * @param <T> Generic types
     */
    public static <T extends Comparable<T>> void sort(T[] arr) {
        Map<Object, Integer> counts = new HashMap<>();
        for (Object ob : arr) {
            counts.put(ob, 1 + counts.getOrDefault(ob, 0));
        }
        System.out.println(Arrays.toString(counts.entrySet().toArray()));
        Comparator<Object> comparator = (o1, o2) -> counts.get(o1).compareTo(counts.get(o2));
        Arrays.sort(arr, comparator);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        Integer[] arr1 = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            arr1[i] = arr[i];
        }
        sort(arr1);
    }

    public static void main(String[] args) {
        sort(new int[]{1, 1, 1, 2, 2, 3}); //primitive types are not comparable
        sort(new Integer[]{1, 1, 1, 2, 2, 3});
    }
}

Last updated