[英]Java Streams Error while calling Method inside filter
我有两个班级如下
package academy.learnprogramming;
public class Employee {
int empId;
int salary;
String name;
String designation;
Employee(int empId, String name, String designation, int salary){
this.empId = empId;
this.name = name;
this.designation = designation;
this.salary = salary;
}
public String toString(){
return "ID = "+empId + ", Name = "+name+", Designation = "+designation+", Salary = "+salary;
}
public String filterData(){
if(empId == 111 && salary > 1000){
return "ID = "+empId + ", Name = "+name+", Designation = "+designation+", Salary = "+salary;
}
return "";
}
}
package academy.learnprogramming;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static List<Employee> employeeList = new ArrayList<Employee>();
public static void main(String[] args) {
Employee employee1 = new Employee(111,"Niranjan","SSE",10000);
Employee employee2 = new Employee(112,"Niramal","SSE-1",10001);
Employee employee3 = new Employee(113,"Nijaguna","SSE-2",10);
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
/*for (Employee employee: employeeList){
System.out.println(employee.toString());
}*/
employeeList.stream().forEach(System.out::println);
System.out.println("****");
//employeeList.stream().filter(employee -> employee.salary > 10000 ).forEach(System.out::println);
employeeList.stream().filter(Employee::filterData).map(employee->employee).collect(Collectors.toList());
System.out.println("*******Sorted list*******");
}
}
我在下面的行中收到错误,说方法参考中的返回类型错误:无法将 java.lang.String 转换为布尔值
employeeList.stream().filter(Employee::filterData).map(employee->employee).collect(Collectors.toList());
有人可以帮忙吗? 学习java概念
如果有人帮助同样会很有帮助
Stream#filter 期望流类型中的函数为布尔值,并将删除该函数返回 false 的任何元素。 Employee#filterData 方法返回一个字符串,因此它不能作为过滤依据的函数。 相反,您需要一个返回布尔值的方法:如果流应该保留该员工,则为 true,如果不应该保留,则为 false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.