JAVA

  minte9
REMEMBERS




Last update:   29-10-2021

One Method

p18 A functional interface has only one abstract method (used as type for lambdas).
 
/**
 * A functional interface has only one abstract method ...
 * used as type for lambdas.
 */

package com.minte9.lambdas.functional_interfaces;
import javax.swing.JButton;
import javax.swing.JFrame;
/*
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
*/

public class OneMethod {
    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JButton button = new JButton("Click me");

        /*
        button.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Button clicked");
                }
            }
        );
        */

        button.addActionListener(event -> { // Look Here
             System.out.println("Button clicked");
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

/*
abstract interface ActionListener extends EventListener {
 
    public abstract void actionPerformed(ActionEvent arg0); 
}
*/

Predicate

Functional interfaces can come in many forms.
 
/**
 * Examples of functional interfaces, using Predicate interface.
 */

package com.minte9.lambdas.functional_interfaces;
import java.util.function.Function;
import java.util.function.Predicate;

public class Predicates {
    public static void main(String[] args) {

        Predicate<Integer> op1 = (x) -> (x % 2 == 0);
        System.out.println(op1.test(36)); 
            // true

        Predicate<String> op2 = new Predicate<>() {
            @Override public boolean test(String t) {
                return t.length() > 3;
            }
        };
        System.out.println(op2.test("abcd")); 
            // true

        Predicate<String> op3 = t -> (t.length() > 3);
        System.out.println(op3.test("abcd")); 
            // true

        Function<Long, Long> op = x -> x + 1;
        System.out.println(op.apply(20L)); 
            // 21
    }
}

/*
package java.util.function;
public abstract interface Predicate<T> {
  
  public abstract  boolean test(T arg0);

  ...
*/

Custom

You can create custom functional interface.
 
/**
 * You can create custom functional interface.
 */

package com.minte9.lambdas.functional_interfaces;

public class Custom {
    public static void main(String[] args) {

        MyFuncInterface s1 = s -> s + "!";
        MyFuncInterface s2 = s -> s + "?";

        System.out.println(s1.run("Hello")); 
            // Hello!
        System.out.println(s2.run("Hello")); 
            // Hello?
    }
}

abstract interface MyFuncInterface {
    String run(String s);
}

Questions     github Lambdas
Streams
        A B C D E F
🔔
1/1