How to write apply function of function Interface in stream.map function?

Given an ArrayList with 5 Employee(id,name,location,salary) objects,write a program to extract the location details of each Employee and store it in an ArrayList, with the help of Function.

I want to use stream.map function for this question.

import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors;  class Employee{     int id;     String name;     String location;     int salary;          Employee(int id,String name,String location,int salary){         this.id=id;         this.name=name;         this.location=location;         this.salary=salary;     } }   public class JAVA8 {     public static void main(String[] args){          ArrayList<Employee> al=new ArrayList<Employee>();          Employee e=new Employee(123,"Muskan","Rajasthan",34000);          Employee e1=new Employee(456,"Sonali","Maharashtra",45003);          Employee e2=new Employee(789,"Khushboo","LaxmanGarh",22222);          Employee e3=new Employee(012,"Minakshi","USA",22);          al.add(e);          al.add(e1);          al.add(e2);          al.add(e3);          Function<Employee,String> f1=(s)->(s.location);          String a;          List<String> li=al.stream()                                 .map(Employee::apply)                                 .collect(Collectors.toList());         }  }   

But I am getting an error at this line – .map(Employee:: apply). I want to use String s=f1.apply(employeeObject) in map. How to do that

Add Comment
2 Answer(s)

There is not apply method in Employee class. You can use the function directly

Function<Employee,String> f1=(s)->(s.location); List<String> li=al.stream().map(f1).collect(Collectors.toList()); 

Or use lambda inside map()

List<String> li=al.stream().map(s->s.location).collect(Collectors.toList()); 
Answered on July 16, 2020.
Add Comment

Employee has no apply method.

You should pass the f1 instance, which implements Function<Employee,String>, to map():

List<String> li=al.stream()                   .map(f1)                   .collect(Collectors.toList()); 

P.S. it would be better to use a getter instead of accessing the instance variable directly:

  • with lambda Function<Employee,String> f1 = s -> s.getLocation();

  • with method reference Function<Employee,String> f1 = Employee::getLocation;

Of course, you can do this without f1:

List<String> li=al.stream()                   .map(Employee::getLocation)                   .collect(Collectors.toList()); 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.