[JAVA] Functional interface introduction

Hello everyone. I would like to introduce a functional interface this time.

Predicate (return value → boolean)

public interface Predicate <T>

Method example:

import java.util.function.Predicate;

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

        Predicate <String> pre = (String username) -> {
            return "admin".equals(username);
        };

        System.out.println(pre.test("manager"));
        System.out.println(pre.test("admin"));
      }
    }

Return value:

false
true

Consumer (no return value)

public interface Consumer<T>
import java.util.function.Consumer;

public class App {
    public static void main( String[] args ) {
        Consumer<String> con = (String message) -> {
            System.out.println("Return message: " + message);
            System.out.println("The message send succeed");
        };
        con.accept("Hello world");
        con.accept("Lambda");
      }
    }

Function

public interface Function<T,R>

Example:

import java.util.function.Function;

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

        Function<String, Integer> fun = (String gender) -> {
            return ("male".equals(gender))?0:1;
        };
        System.out.println(fun.apply("male"));
        System.out.println(fun.apply("female"));
      }
    }

result:

0
1

Recommended Posts

Functional interface introduction
[Java] Functional interface
About Java functional interface
java standard functional interface
Functional interface review notes
[Java] Functional interface / lambda expression
interface
Introduction to Functional Programming (Java, Javascript)
Imitate Java's functional interface in Kotlin
Lombok ① Introduction
Introduction (self-introduction)
Interface benefits
java (interface)
new interface
[java] interface
[Java] Introduction
Introduction (editing)