Java Predefined Functional Interface.

Java Predefined Functional Interface

  • The java.util.function package defines several predefined functional interfaces that you can use when creating lambda expressions or method references.
  • They are widely used throughout the Java API.
    Here are some of the most important:
    Functional Interface Abstract Method Function descriptor Description
    Consumer<T> accept(T t) T -> void Represents an operation that accepts a single input argument and returns no result.
    Function<T, R> apply(T t) T -> R Represents a function that accepts one argument and produces a result.
    Predicate<T> test(T t) T -> boolean Represents a predicate (boolean-valued function) of one argument.
    Supplier<T> get() () -> T Represents a supplier of results.
    Example using Consumer<T>:
    public class ConsumerApp {
    
      public static void main(String[] args) {
        String[] players = {"Rafael Nadal", "Novak Djokovic", 
          "Stanislas Wawrinka", "David Ferrer",
          "Roger Federer", "Andy Murray", "Tomas Berdych", 
          "Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
        // Show the list of players
        System.out.print("Show the list of players:\n");
        // void forEach(Consumer<? super T> action)
        Arrays.asList(players).forEach((player) -> System.out.println(player));
      }
    }
    
    The result of this is:
    Show the list of players:
    Rafael Nadal
    Novak Djokovic
    Stanislas Wawrinka
    David Ferrer
    Roger Federer
    Andy Murray
    Tomas Berdych
    Juan Martin Del Potro
    Richard Gasquet
    John Isner
    You can download this example here (needed tools can be found in the right menu on this page).
    Example using Function<T, R>:
    public class FunctionApp {
      public static void main(String[] args) {
        String[] players = {"Rafael Nadal", "Novak Djokovic",
          "Stanislas Wawrinka", "David Ferrer", 
          "Roger Federer", "Andy Murray",
          "Tomas Berdych", "Juan Martin Del Potro", 
          "Richard Gasquet", "John Isner"};
        Function<String[],String> converter = (all)-> {
          String names= ""; 
          for (String n : all){
            String forname=n.substring(0, n.indexOf(" "));
            forname=n.substring(n.indexOf(" "))+" "+forname;
            names+=forname+"\n";
          }
          return names;
        };
        System.out.println(converter.apply(players));
      }
    }
    
    The result of this is:
     Nadal Rafael
     Djokovic Novak
     Wawrinka Stanislas
     Ferrer David
     Federer Roger
     Murray Andy
     Berdych Tomas
     Martin Del Potro Juan
     Gasquet Richard
     Isner John
    
    You can download this example here (needed tools can be found in the right menu on this page)
    Example using Predicate<T>:
    public class PredicateApp {
      private static List getBeginWith(List<String> list, Predicate<String> valid) {
        List<String> selected = new ArrayList<>();
        list.forEach(player -> {
          if (valid.test(player)) {
            selected.add(player);
          }
        });
        return selected;
      }
    
      public static void main(String[] args) {
        String[] players = {"Rafael Nadal", "Novak Djokovic",
          "Stanislas Wawrinka", "David Ferrer",
          "Roger Federer", "Andy Murray", "Tomas Berdych", 
          "Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
        List playerList = Arrays.asList(players);
        System.out.println(getBeginWith(playerList,(s)->s.startsWith("R")));
        System.out.println(getBeginWith(playerList,(s)->s.contains("D")));
        System.out.println(getBeginWith(playerList,(s)->s.endsWith("er")));
      }
    }
    
    The result of this is:
    [Rafael Nadal, Roger Federer, Richard Gasquet]
    [Novak Djokovic, David Ferrer, Juan Martin Del Potro]
    [David Ferrer, Roger Federer, John Isner]
    You can download this example here (needed tools can be found in the right menu on this page)
    Example using Supplier<T>:
    public class SupplierApp {
      private static void printNames(Supplier<String> arg) {
        System.out.println(arg.get());
      }
      private static void listBeginWith(List<String> list, Predicate<String> valid) {
        printNames(()->"\nList of players:");
        list.forEach(player -> {
          if (valid.test(player)) {
            printNames(()->player);
          }
        });
      }
      public static void main(String[] args) {
        String[] players = {"Rafael Nadal", "Novak Djokovic", 
          "Stanislas Wawrinka", "David Ferrer",
          "Roger Federer", "Andy Murray", "Tomas Berdych", 
          "Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
        List playerList = Arrays.asList(players);
        // print which starts with 'R'
        listBeginWith(playerList, (s) -> s.startsWith("R"));
        listBeginWith(playerList, (s) -> s.contains("D"));
        listBeginWith(playerList, (s) -> s.endsWith("er"));
      }
    }
    
    The result of this is:
    List of players:
    Rafael Nadal
    Roger Federer
    Richard Gasquet
    
    List of players:
    Novak Djokovic
    David Ferrer
    Juan Martin Del Potro
    
    List of players:
    David Ferrer
    Roger Federer
    John Isner
    You can download this example here (needed tools can be found in the right menu on this page)
  • The API contains other predefined interfaces that can be used as functional interface.
    Here are some of them:
    Functional Interface Abstract Method Function descriptor Description
    Runnable run() () -> void When a Thread starts the Runnable object, the method run() will bee executed.
    ActionListener actionPerformed (ActionEvent) ActionEvent -> void This Listener receives action events and the method actionPerformed(ActionEvent e) execute.
    Comparator<T> compare(T , T ) (T,T) -> int Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
    Observer Update (Observable, Object ) (Observable, Object ) -> void This method is called whenever the observed object is changed.
    Example using Runnable:
    public class RunnableApp {
      public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + 
             " application : is running");
     // Impementation without using lambda
        Thread thread2 = new Thread(new Runnable() {
          @Override
          public void run() {
            System.out.println(Thread.currentThread().getName() + " is running");
          }
        });
        thread2.start();
    // Using Lambda Runnable
        Runnable task3 = () -> {
          System.out.println(Thread.currentThread().getName() + " is running");
        };
        new Thread(task3).start();
    // All in one statement using Lambda and Runnable interface     
        new Thread(() -> {
          System.out.println(Thread.currentThread().getName() + " is running");
        }).start();
      }
    }
    
    The result of this is:
    main application : is running
    Thread-0 is running
    Thread-1 is running
    Thread-2 is running
    You can download this example here (needed tools can be found in the right menu on this page)
    Example using ActionListener:
    public class ListenerApp {
    // static swing helper method
      static private void setAppSize(JFrame frame, int width, int heigth) {
        int widthExt = 20;
        int heightExt = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setBounds((screenSize.width - (width + widthExt)) / 2, 
                screenSize.height / 20, width + widthExt, heigth + heightExt);
      }
      public static void main(String[] args) {
        JButton testButton = new JButton("Test Button");
        // Without Lambda add listener as an anonymous object implementation
        testButton.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            System.out.println("Click Detected by anonymous object");
          }
        });
        // add listener with lambda expression
        testButton.addActionListener(
                e -> System.out.println("Click Detected by Lambda Listner"));
        // Swing stuff
        JFrame frame = new JFrame("Listener APP");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setAppSize(frame, 300, 200);
        frame.add(testButton, BorderLayout.CENTER);
        frame.setVisible(true);
      }
    }
    
    The result of this is:
    Pressing the button result in:
    Click Detected by Lambda Listner
    Click Detected by anonymous objec
    You can download this example here (needed tools can be found in the right menu on this page)
    Example using Comparator<T>:
    public class ComparatorApp {
      public static void main(String[] args) {
        List<Person> personList = Person.createShortList();
        // Sort on persons surname with abstract inner class object implementation
        Collections.sort(personList, new Comparator<Person>() {
          @Override
          public int compare(Person p1, Person p2) {
            return p1.getSurName().compareTo(p2.getSurName());
          }
        });
        System.out.println("=== Sorted ascending Surname ===");
        personList.forEach(p -> p.printName());
        // Use Lambda and print all persons on ascending GivenName. 
        System.out.println("=== Sorted ascending Givenname ===");
        Collections.sort(personList, 
          (Person p1, Person p2) -> p1.getGivenName().compareTo(p2.getGivenName()));
        personList.forEach(p -> p.printName());
        // Use Lambda and print all persons on descending SurName
        System.out.println("=== Sorted descending Surname ===");
        Collections.sort(personList, 
          (p1, p2) -> p2.getSurName().compareTo(p1.getSurName()));
        personList.forEach(p -> p.printName());
      }
    }
    // Requuired Person.java file
    public class Person {
      private String givenName;
      private String surName;
    ...
      public static List<Person> createShortList(){
    ...
      }
    }
    
    The result of this is:
    === Sorted ascending Surname ===
    Name: Joe Bailey
    Name: Bob Baker
    Name: Jane Doe
    Name: John Doe
    Name: James Johnson
    Name: Betty Jones
    Name: Phil Smith
    === Sorted ascending Givenname ===
    Name: Betty Jones
    Name: Bob Baker
    Name: James Johnson
    Name: Jane Doe
    Name: Joe Bailey
    Name: John Doe
    Name: Phil Smith
    === Sorted descending Surname ===
    Name: Phil Smith
    Name: Betty Jones
    Name: James Johnson
    Name: Jane Doe
    Name: John Doe
    Name: Bob Baker
    Name: Joe Bailey
    You can download this example here (needed tools can be found in the right menu on this page)
    Example using Observer:
    public class ObserverApp extends Observable {
      public void changeMessage(String message) {
        setChanged();
        notifyObservers(message);
      }
      public static void main(String[] args) {
        ObserverApp board = new ObserverApp();
        // add Observer objects
        board.addObserver(new Student("Bob").getObserver());
        board.addObserver(new Student("Joe").getObserver());
        // create an event
        board.changeMessage("More Homework!");
      }
    }
    
    class Student {
      private String name;
      // Lambda on observer
      private Observer observer = 
        (o, arg) -> System.out.println(name + " got message: " + arg);
      // this is the same as:
      //  private Observer observer = new Observer(){
      //    @Override
      //    public void update(Observable o, Object arg) {
      //      System.out.println(name+" got message: " + arg);
      //    }
      //  };
      public Student(String name) {
        this.name = name;
      }
      public Observer getObserver() {
        return observer;
      }
    }
    
    The result of this is:
    Joe got message: More Homework!
    Bob got message: More Homework!
    You can download this example here (needed tools can be found in the right menu on this page)
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.