在以下程序中,toString()如何与谓词一起使用

时间:2018-09-13 06:39:34

标签: java-8 tostring predicate

任何人都可以解释toString()函数如何与此谓词一起使用。我理解了lambda表达式,但是如何调用toString()函数。

import java.util.function.*;
import java.util.*;
class Demo{
public static void main(String arv[]){
    HashSet <Employee> hs = new HashSet<>();
    hs.add(new Employee("A",40000,25,"CSE"));
    hs.add(new Employee("B",50000,26,"CSE"));
    hs.add(new Employee("C",54000,30,"ECEadsa"));
    hs.add(new Employee("D",45000,25,"ECE"));
    hs.add(new Employee("E",60000,32,"CSE"));
    Predicate <Employee> emp = t -> t.salary > 50000;
    Predicate <Employee> emp1 = emp.and( t -> t.department.length()>5);
    for(Employee e: hs)
    if (emp1.test(e))
    System.out.println(e);
                                     }
         }
class Employee{
   String name;
   double salary;
   int age;
   String department;
   Employee(String n, double s, int a, String d){
   name = n;
   salary = s;
   age = a;
   department = d;
              }
public String toString(){
   return " name = "+name+" salary = "+salary+" age = "+age+" department = "+department;
                        }
               }

输出: 名称= C薪水= 54000.0年龄= 30个部门= ECEadsa

2 个答案:

答案 0 :(得分:1)

您已经添加了用于打印Employee的代码,只要存在,则打印该类的任何对象的toString()方法都将被调用(如果存在),否则会调用

  for(Employee e: hs)
    if (emp1.test(e))
    System.out.println(e);
              }
         }

对于具有department.length()的员工> 5个打印逻辑System.out.println(e);被称为

答案 1 :(得分:0)

在PrintStream类中,println(Object x)方法使用String.valueOf(x),该方法调用对象的toString()。 如果尚未覆盖toString()方法,则将使用Object类的默认实现。