首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用过滤器中的方法时出现的Java流错误

调用过滤器中的方法时出现的Java流错误
EN

Stack Overflow用户
提问于 2022-07-19 11:16:51
回答 1查看 27关注 0票数 -1

我有两堂课,如下

代码语言:javascript
复制
    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概念

如果有人帮上同样的忙会很有帮助

EN

回答 1

Stack Overflow用户

发布于 2022-07-19 11:18:52

Stream#filter期望一个函数从流类型到布尔类型,并将删除该函数返回false的所有元素。Employee#filterData方法返回一个字符串,因此它不作为要筛选的函数工作。相反,您需要一个返回布尔值的方法:如果流应该保留该员工,则返回true;如果不应该,则需要返回false。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73035926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档