$show=/label

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

SHARE:

A quick guide to Java 8 Function Functional Interface and realtime example programs. Function Chain Methods andThen(), identity() Example programs.

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.

Java 8 Function Examples 

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,71,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,7,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Function Examples (apply() and Chain Methods andThen(), identity())
Function Examples (apply() and Chain Methods andThen(), identity())
A quick guide to Java 8 Function Functional Interface and realtime example programs. Function Chain Methods andThen(), identity() Example programs.
https://1.bp.blogspot.com/-Q71U0Ngz2bI/Xq1cRYDZFuI/AAAAAAAACnI/j8BRpWvLUrQGFAyCNLtKXi_szQYiWt2GQCLcBGAsYHQ/s640/Java%2B8%2BFunction%2BExamples%2B%2528apply%2528%2529%2Band%2BChain%2BMethods%2BandThen%2528%2529%252C%2Bidentity%2528%2529%2529.png
https://1.bp.blogspot.com/-Q71U0Ngz2bI/Xq1cRYDZFuI/AAAAAAAACnI/j8BRpWvLUrQGFAyCNLtKXi_szQYiWt2GQCLcBGAsYHQ/s72-c/Java%2B8%2BFunction%2BExamples%2B%2528apply%2528%2529%2Band%2BChain%2BMethods%2BandThen%2528%2529%252C%2Bidentity%2528%2529%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/java-8-function-examples.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/java-8-function-examples.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content