Java 8 - Bi Function
Bi Function:
* When we need to access two input argument and we need to return some values, then we need to go for BiFunction.
Syntax:
interface BiFunction<T,U,R>
{
public R apply(T t,U u);
//default method andThen()
}
Example:
class Test
{
public static void main(String[] args)
{
BiFunction<Integer,Integer,Integer> f=(a,b)->a*b;
System.out.println(f.apply(10,20));
System.out.println(f.apply(100,200));
}
}
Example: Create Student Object by taking name, roll no as input
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Student> l = new ArrayList<Student>();
BiFunction<String,Integer,Student> f=(name,rollno)->new Student(name,rollno);
l.add(f.apply("Durga",100));
l.add(f.apply("Ravi",200));
l.add(f.apply("Shiva",300));
l.add(f.apply("Pavan",400));
for(Student s : l)
{
System.out.println("Student Name:"+s.name);
System.out.println("Student Rollno:"+s.rollno);
System.out.println();
}
}
}
Output:
Student Name:Durga
Student Rollno:100
Student Name:Ravi
Student Rollno:200
Student Name:Shiva
Student Rollno:300
Student Name:Pavan
Student Rollno:400
* When we need to access two input argument and we need to return some values, then we need to go for BiFunction.
Syntax:
interface BiFunction<T,U,R>
{
public R apply(T t,U u);
//default method andThen()
}
Example:
class Test
{
public static void main(String[] args)
{
BiFunction<Integer,Integer,Integer> f=(a,b)->a*b;
System.out.println(f.apply(10,20));
System.out.println(f.apply(100,200));
}
}
Example: Create Student Object by taking name, roll no as input
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Student> l = new ArrayList<Student>();
BiFunction<String,Integer,Student> f=(name,rollno)->new Student(name,rollno);
l.add(f.apply("Durga",100));
l.add(f.apply("Ravi",200));
l.add(f.apply("Shiva",300));
l.add(f.apply("Pavan",400));
for(Student s : l)
{
System.out.println("Student Name:"+s.name);
System.out.println("Student Rollno:"+s.rollno);
System.out.println();
}
}
}
Output:
Student Name:Durga
Student Rollno:100
Student Name:Ravi
Student Rollno:200
Student Name:Shiva
Student Rollno:300
Student Name:Pavan
Student Rollno:400
Comments
Post a Comment