Java 8 - BiConsumer
BiConsumer:
* When we need to access two input argument and we need to return some values, then we need to go for BiConsumer.
Syntax:
interface BiConsumer<T,U>
{
public void accept(T t,U u);
//default method andThen()
}
Example: To increment employee Salary
class Employee
{
String name;
double salary;
Employee(String name,double salary)
{
this.name=name;
this.salary=salary;
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Employee> l= new ArrayList<Employee>();
populate(l);
BiConsumer<Employee,Double> c=(e,d)->e.salary=e.salary+d;
for(Employee e:l)
{
c.accept(e,500.0);
}
for(Employee e:l)
{
System.out.println("Employee Name:"+e.name);
System.out.println("Employee Salary:"+e.salary);
System.out.println();
}
}
public static void populate(ArrayList<Employee> l)
{
l.add(new Employee("Durga",1000));
l.add(new Employee("Sunny",2000));
l.add(new Employee("Bunny",3000));
l.add(new Employee("Chinny",4000));
}
}
Output:
Employee Name:Durga
Employee Salary:1500.0
Employee Name:Sunny
Employee Salary:2500.0
Employee Name:Bunny
Employee Salary:3500.0
Employee Name:Chinny
Employee Salary:4500.0
* When we need to access two input argument and we need to return some values, then we need to go for BiConsumer.
Syntax:
interface BiConsumer<T,U>
{
public void accept(T t,U u);
//default method andThen()
}
Example: To increment employee Salary
class Employee
{
String name;
double salary;
Employee(String name,double salary)
{
this.name=name;
this.salary=salary;
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Employee> l= new ArrayList<Employee>();
populate(l);
BiConsumer<Employee,Double> c=(e,d)->e.salary=e.salary+d;
for(Employee e:l)
{
c.accept(e,500.0);
}
for(Employee e:l)
{
System.out.println("Employee Name:"+e.name);
System.out.println("Employee Salary:"+e.salary);
System.out.println();
}
}
public static void populate(ArrayList<Employee> l)
{
l.add(new Employee("Durga",1000));
l.add(new Employee("Sunny",2000));
l.add(new Employee("Bunny",3000));
l.add(new Employee("Chinny",4000));
}
}
Output:
Employee Name:Durga
Employee Salary:1500.0
Employee Name:Sunny
Employee Salary:2500.0
Employee Name:Bunny
Employee Salary:3500.0
Employee Name:Chinny
Employee Salary:4500.0
Comments
Post a Comment