Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, December 1, 2020

Function Interface in Java with Examples (apply() and Chain Methods andThen(), identity())

1.Introduction


In this tutorial, You'll learn how to use Function in Java 8 and Function Examples. This is part of core Functional Interfaces in Java 8 new concepts.

This is added as part of java 8 in java.util package.

Java 8 Function Examples (apply() and Chain Methods andThen(), identity())


Function interface is mainly useful if a method takes some input and produces output always.

First, Understand how it is implemented internally and how this Function can be leveraged in real-time applications.


2. Java 8 Function<T, R> Internal Implementation


First, Look at the below internal code how it is declared and provided an implementation in the default methods.

API Note: Represents a function that accepts one argument and produces a result.


You can define in the interface default methods which have a body. These are introduced in Java 8.

Observer the code and it needs two types T and R. And also it as a one functional method R apply(T t) which means it takes one input argument and returns a value.

Where T and R defined as follows.

T --> What is the input type
R --> What type of value is returned.     

[package java.util.function;
import java.util.Objects;

@FunctionalInterfacepublic interface Function<T, R> {
 
    R apply(T t);
 
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
 
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
 
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}]


And also this has two default and one static additional to the apply() method.

apply() method is called as Functional Method.

3. Java 8 Function<T, R> Example to convert Integer to String and Calculate String length

Function Examples:

package com.javaprogramto.java8.functional.interfaces.function;

import java.util.function.Function;

public class java8FunctionExample {

    public static void main(String[] args) {

        Function<String, Integer> function = str -> str.length();

        int length = function.apply("Hello world");
        System.out.println("Fucntion to find string length :" + length);

        Function<Integer, String> function2 = number -> String.valueOf(number) + " is now String";

        String output = function2.apply(1260);
        System.out.println("Funtion to covnert Integer to String : "+output);
    }
}

Output:

[Fucntion to find string length :11
Funtion to covnert Integer to String : 1260 is now String]

4. Java 8 Function<T, R> Example to convert Employee to String

Function Examples:

Employee.java

package com.javaprogramto.models;

public class Employee {

    private int id;
    private String fullName;
    private int age;

    public Employee(int id, String fullName, int age) {
        this.id = id;
        this.fullName = fullName;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", fullName='" + fullName + '\'' +
                ", age=" + age +
                '}';
    }
}


Function Examples Main Program:

package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class EmployeeFuntionEample {

    public static void main(String[] args) {

        Function<Employee, String> empString = employee -> employee.getAge() + " - " + employee.getFullName();

        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee(100, "Jhon Paul", 25));
        list.add(new Employee(101, "Narmad Rao", 30));

        for (Employee emp : list) {
            String empInStr = empString.apply(emp);
            System.out.println(empInStr);
        }

    }
}

Output:

[25 - Jhon Paul
30 - Narmad Rao]

5. Java 8 Function<T, R> Example to convert List<Employee> to Map<Integer, Employee>

Function Examples:


package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class FunctionListToMap {

  static Logger logger = LoggerFactory.getLogger(FunctionListToMap.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();

        // Createing a list        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee(100, "Jhon Paul", 25));
        list.add(new Employee(101, "Narmad Rao", 30));

        // Creating Function to convert List to Map.        Function<List<Employee>, Map<Integer, Employee>> listToMap = employees -> {

            Map<Integer, Employee> newMap = new HashMap<>();
            for (Employee e : employees
            ) {
                newMap.put(e.getId(), e);
            }
            return newMap;
        };

        Map<Integer, Employee> empMap = listToMap.apply(list);
        logger.info("List to Map : " + empMap);
    }
}

Output:

[List to Map : {100=Employee{id=100, fullName='Jhon Paul', age=25}, 101=Employee{id=101, fullName='Narmad Rao', age=30}}]

6. Java 8 Function<T, R> chain(), andThen(), identity() Method Examples



Function<T,T> identity() : This is a static method and returns a function that always returns its input argument.
Function andThen(Function after): This is a default method and will be invoked after the current Function apply() method execution.

identity() example to find the first non-repeated character.

Function Examples:

You'll get a better understanding once you see the below example program.

package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FunctionMethodExamples {

    public static void main(String[] args) {

        Function<Employee, String> empToStringFunction = emp -> emp.getFullName();

        Function<String, Integer> stringToIntFunction = str -> str.length();

        Function<Integer, Integer> squereFunction = numner -> numner * numner;

        // chain() method example        Integer squere = empToStringFunction.andThen(stringToIntFunction).andThen(squereFunction).apply(new Employee(500, "Lady Gaga", 50));

        System.out.println("andThen() example to get Employee name length squere : " + squere);

        // identity() example        String input = "aaaaa bbbbb";
        Map chars = input.codePoints().mapToObj(cp -> cp)
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));

        System.out.println("identity chars "+chars);
    }


}

Output:

[andThen() example to get Employee name length squere : 81
identity chars {97=5, 32=1, 98=5}]

7. Conclusion


In conclusion, You've seen the example programs on Function Functional Interface.

And also have seen examples to find the repeated characters count in a string.

Finally, Examples to convert Integer to String, List to Map, and at last find the string length.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.


If you have any queries please post in the comment section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.