toString()如何在以下程序中使用Predicate

问题描述 投票:-2回答:2

任何人都可以解释一下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;
                        }
               }

输出:name = C salary = 54000.0 age = 30 department = ECEadsa

java-8 tostring predicate
2个回答
1
投票

您已经添加了用于打印Employee的代码,当您打印任何对象时,如果存在,则为该类调用toString()方法调用其他toString的方法

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

对于具有department.length()> 5的打印逻辑System.out.println(e)的员工;叫做


0
投票

在PrintStream类中,println(Object x)方法使用String.valueOf(x),它调用对象的toString()。如果您没有覆盖toString()方法,则可以使用Object类的默认实现。

© www.soinside.com 2019 - 2024. All rights reserved.