给定一个包含 5 个 Employee(id,name,location,salary) 对象的 ArrayList,借助 Function 编写一个程序来提取每个 Employee 的位置详细信息并将其存储在 ArrayList 中。
我想使用stream.map函数来解决这个问题。
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());
}
}
但是我在这一行收到错误 - .map(Employee::apply)
。
我想在 map 中使用 String s=f1.apply(employeeObject)
。如何做到这一点
最佳答案
Employee
没有apply
方法。
您应该传递f1
实例,它实现 Function<Employee,String>
, 至map()
:
List<String> li=al.stream()
.map(f1)
.collect(Collectors.toList());
附注最好使用 getter 而不是直接访问实例变量:
使用 lambda
Function<Employee,String> f1 = s -> s.getLocation();
带有方法引用
Function<Employee,String> f1 = Employee::getLocation;
当然,您可以在没有 f1
的情况下执行此操作:
List<String> li=al.stream()
.map(Employee::getLocation)
.collect(Collectors.toList());
关于java - 如何在stream.map函数中编写函数接口(interface)的apply函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62859279/