×

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

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.