[英]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.