• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Function Example – Functional Interface

December 21, 2020 by javainterviewpoint Leave a Comment

The Function Functional interface takes a single input and returns any value. The function interface is located in java.util.function package. It has a Single Abstract Method (SAM) apply(), which accepts the generic object type T and returns object type R.

Java Function Example

Java Function Example

Whenever we create a Lambda Expression, which takes a single input and can return any value, then the Function can be used as a target for the lambda expression. The Function interface is similar to Predicate functional interface; the only change is the return type.

Methods in Function Interface

  1. R apply(T t) – This method takes a single generic argument T and returns an object of type R
  2. default <V> Function<T,V> andThen(Function<? super R,? extends V> after) – This is a default method, returns a composed function. The input function will be executed and on the result after function will be executed.
  3. default <V> Function<V,R> compose(Function<? super V,? extends T> before) – This is a default method, returns a composed function. The before function will be executed first and on the result input function will be executed.
  4. static <T> Function<T,T> identity() – This static method returns its input argument.

1. Java Function apply() method example

The apply() method of the Function interface can take any object type as an argument and can return any object type.

Let’s build a Function that returns the capitalizes of the String passed to it.

package com.javainterviewpoint;

import java.util.function.Function;

public class ToUpperFunction
{
   public static void main(String[] args)
   {
      Function<String, String> capitalize = val -> val.toUpperCase();
      System.out.println(capitalize.apply("WeLcoMe"));
      System.out.println(capitalize.apply("JaVaInTeRvIeWpOiNt"));
   }
}

Output:

WELCOME
JAVAINTERVIEWPOINT

In the above code, we have created a Function that capitalizes the string passed to it.

Function<String, String> capitalize = val -> val.toUpperCase();

We can invoke the capitalize function by passing a string argument to the apply() method.

We have passed a string as input and got a string as output. There are no rules that the return type has to be the same as the input type.

Let’s create a new Function, which takes in a string input and returns the length of the string, which will be an integer output.

package com.javainterviewpoint;

import java.util.function.Function;

public class LengthOfString
{
   public static void main(String[] args)
   {
      Function<String, Integer> length = val -> val.length();

      System.out.println("Length of \"Hello\" is: " + length.apply("Hello"));
      System.out.println("Length of \"Welcome\" is: " + length.apply("Welcome"));
   }
}

Output:

Length of "Hello" is: 5
Length of "Welcome" is: 7

The Function interface can also be used in the Streams; the map() method of the stream takes the Function as its argument.

Let’s create a Function which squares the number passed to it.

package com.javainterviewpoint;

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

public class SquareFunction
{
   public static void main(String[] args)
   {
      Function<Integer, Integer> squareFunction = num -> num * num;

      List numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

      numberList.stream().map(num -> (squareFunction.apply(num)))
            .forEach(System.out::println);
   }
}

Output:

1
4
9
16
25
36
49
64
81

The Function can be used on custom objects as well. Let’s create a function that adds an internal mark of 20 to each student.

Student.java

package com.javainterviewpoint;

public class Student
{
   private int id;
   private int mark;
   private String name;

   public Student()
   {
      super();
   }
   public Student(int id, int mark, String name)
   {
      super();
      this.id = id;
      this.mark = mark;
      this.name = name;
   }
   public int getId()
   {
      return id;
   }
   public void setId(int id)
   {
      this.id = id;
   }
   public int getMark()
   {
      return mark;
   }
   public void setMark(int mark)
   {
      this.mark = mark;
   }
   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
}

StudentPredicate.java

package com.javainterviewpoint;

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

public class StudentFunction
{
   public static void main(String[] args)
   {
      List<Student> studentList = new ArrayList();

      studentList.add(new Student(1, 45, "Alice"));
      studentList.add(new Student(2, 65, "Bob"));
      studentList.add(new Student(3, 80, "Clair"));
      studentList.add(new Student(4, 20, "Dom"));

      Function<Integer, Integer> markIncrement = mark -> mark + 20;

      System.out.println("** Student marks after adding internal marks **");
      studentList.stream()
            .map(student -> markIncrement.apply(student.getMark()))
            .forEach(System.out::println);
   }
}

In the above, we have created a simple function which adds 20 marks to each student.

Output:

** Student marks after adding internal marks **
65
85
100
40

2. Java Function andThen() method example

The andThen() method of the Function interface, the input function will be executed first, and on the result the second function (andThen) will be executed.

We will be performing same operation which we did in the above code, but this time we will use the two functions and andThen method.

package com.javainterviewpoint;

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

public class StudentFunction {
	public static void main(String[] args) {
		List<Student> studentList = new ArrayList();
		studentList.add(new Student(1, 25, "Adam"));
		studentList.add(new Student(2, 35, "Bob"));
		studentList.add(new Student(3, 45, "Danny"));
		studentList.add(new Student(4, 55, "Will"));
		Function<Student, Integer> getMark = student -> student.getMark();
		Function<Integer, Integer> markIncrement = mark -> mark + 20;
		System.out.println("** Student marks after adding internal marks **");
		studentList.stream().map(student -> getMark.andThen(markIncrement).apply(student)).forEach(System.out::println);
	}
}

In the above, we have the first function, getMark takes the Student object as input and returns the student’s marks. The second function, markIncrement, add 20 marks to each student.

Since we have used getMark.andThen(markIncrement), the getMark function will be executed first, and on top of it, the markIncrement get executed.

Output:

** Student marks after adding internal marks **
45
55
65
75

3. compose() method example

The compose() method is just the reverse of the andThen() method. The second functional interface will be executed first and followed by the first functional interface.

package com.javainterviewpoint;

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

public class StudentFunction {
	public static void main(String[] args) {
		List studentList = new ArrayList();
		studentList.add(new Student(1, 25, "Adam"));
		studentList.add(new Student(2, 35, "Bob"));
		studentList.add(new Student(3, 45, "Danny"));
		studentList.add(new Student(4, 55, "Will"));
		Function<Student, String> getName = student -> student.getName();
		Function<String, String> addCountry = name -> name + " US";
		System.out.println("** Student after adding Country **");
		studentList.stream().map(student -> addCountry.compose(getName).apply(student)).forEach(System.out::println);
	}
}

We have the second function getName will be executed first and followed by addCountry function.

** Student after adding Country **
Adam US
Bob US
Danny US
Will US

Filed Under: Java Tagged With: Function, Function Example, Function Interface, Functional Interface, Java Function Example, Java Function Interface

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·