×

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function package contains it.

Let us have some knowledge about the Functional interfaces.

Functional interfaces

Functional interfaces are interfaces that only have one abstract method. There can be as many default static methods as needed, but there can only be one abstract method. Additionally, object class methods may be declared.

Single Abstract Method Interfaces, or SAM Interfaces, are another name for functional interfaces. It is a newer version in Java that aids in the development of functional programming techniques.

@FunctionalInterface  
public interface BiFunction<T,U,R>  

The three type-parameters that the interface accepts are as follows:

T: It stands for the function's initial argument.

U: It stands for the function's second argument.

R: It stands for the function's outcome.

The description that may be expressed as (T, U)->R consists of T, U, and R.

Methods of BiFunction Interface

The interface offers the two techniques listed below:

  • apply()
  • andThen()

The BiFunctional apply() method

The apply() method applies the specified inputs to the operation and returns the function's outcome.
its syntax is:

R apply(T t, U u) 

The Parameters:

t: It stands in for the initial function parameter.

u: The letter "u" stands for the second function parameter.

Returns:

The function's output is returned.

Example1:

Let the name of the file is BiFunctionApplyDemo.java

import java.util.function.BiFunction;  
import java.util.function.Function;  
public class BiFunctionApplyDemo.java   
{  
public static void main(String args[])   
{  
BiFunction <Integer, Integer, Integer> bkobj = (s, h) -> s + h;  
// applying the method apply()
System.out.println("The sum of the s and the h is: " + bkobj.apply(47, 22));  
}   
}  

Output:

The sum of the s and the h is: 69

Method using a BiFunction and Then()

A composite function is the result. It indicates that the method applies the before function first, followed by the after function. The operator of the combined function is informed of any exceptions that either function's evaluation throws.

Syntax:

default <V> BiFunction<T,U,V> andThen(Function<? super X,? extends S> later)

The Type-Parameter:

V: This letter stands for the output type of both the composed function and the after() function.

Parameters are:

after: It is applicable following this operation.

Returns:

A composite function is the result. It indicates that the method applies the before function first, followed by the after function.

If after is null, the procedure raises a NullPointerException.

Example1:

BiFunctionAndThenDemo.java

import java.util.function.BiFunction;  
import java.util.function.Function;  
public class BiFunctionAndThenExample  
{  
public static void main(String args[])   
{  
// carries out multiplication
BiFunction <Integer, Integer, Integer> bsobj = (x, y) -> x * y;  
// carries out division
Function <Integer, Integer> sobj = (k) -> k / 2;  
// functional composition
System.out.println("The outcome is: " + bsobj.andThen(kobj).apply(10, 10));
}  
}  

Output:

The outcome is: 50

Let's use a Java application to implement the two aforementioned techniques to better understand how the BiFunction interface functions.

Example for Bifunction

BiFunctionDemo2.java

import java.util.function.BiFunction;  
import java.util.function.Function;  
public class BiFunctionDemo2 
{  
public static void main(String args[])   
{  
// a simple use of apply()
BiFunction<Integer, Integer, Integer> f3 = (x, y) -> x + y;  
System.out.println(f1.apply(42, 27)); //it returns and also print 69 
// a simple andThen() illustration
Function<Integer, Integer> f9 = x -> x * x;  
System.out.println(f3.andThen(f9).apply(31, 13));  
}  
}  

Output:

69
1936

We can see from the above program, the statement in the above that is System.out.println(f3.andThen(f9).apply(2, 3)); It can be simply written as show below:

Integer r3 = f3.apply(31, 13); 
Integer r9 = f9.apply(r3); 
System.out.println(r9); //It returns and also print 1936

Let us have a look at another example program.

BiFunctionDemo9.java

import java.util.function.BiFunction;  
import java.util.function.Function;  
import java.util.*;  
public class BiFunctionDemo9   
{  
public static void main(String args[])   
{  
// the creation of a Map instance
Map<Integer, String> map = new HashMap<>();  
// updating the Map with values
map.put(10, "Janardhan");  
map.put(11, "Hymavathi");  
map.put(12, "Hemanth");  
map.put(13, "Swetha");  
map.put(14, "Archana");  
map.put(15, "Puppy");  
map.put(16, "Bandu");  
// To get the quantity of occurrences, use Collections.frequency
BiFunction<Integer, String, String> s = (key, value) -> "[Key="+key+", "+value+"("+Collections.frequency(map.values(), value)+")]";  
// traverse the Map iteratively
map.forEach((h,p)-> System.out.println(f.apply(h, p)));  
}  
}  

Output:

[Key=10, Janardhan(10)]
[Key=11, Hymavathi(11)]
[Key=12, Hemanth(10)]
[Key=13, Swetha(10)]
[Key=14, Archana(10)]
[Key=15, Puppy(10)]
[Key=16, Bandu(11)]   

Related Topics

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.