如何过滤Set?

时间:2014-07-21 07:48:45

标签: java foreach set

在下面的代码中我是迭代集合在这里我需要从集合中获取一个对象,其中主要部分为真,状态是活动的,我可以如何减少一步执行的代码。

Set<EmployeeDeparment> dep = p.getRequestEmpId().getEmpdep();       
if (!dep.isEmpty()) {
    for (EmployeeDeparment employeeDeparment : dep) {
        if (employeeDeparment.isPrimarydept() == true && employeeDeparment.isStatus() == true) {
            System.out.println("inside the employeedep");
            leaveRequestForm.setApprovalauthority(employeeDeparment.getReportingTo().getFirstname() + "" + employeeDeparment.getReportingTo().getLastname());
        }
    }
} else {
     leaveRequestForm.setApprovalauthority("Approvalauthority not Configured");
}

更新

List<EmployeeDeparment> beerDrinkers = select(persons, having(on(EmployeeDeparment.class).isPrimarydept(),
                        true));

这给出了编译时错误。

2 个答案:

答案 0 :(得分:0)

您可以使用Guava的Iterables.filter()方法。

你的谓词将是这样的:

Predicate<EmployeeDeparment> predicate = new Predicate<EmployeeDeparment>() {

public boolean apply(EmployeeDeparment employeeDeparment){
    return employeeDeparment.isPrimarydept() == true && employeeDeparment.isStatus() == true;
}

您的循环将是:

for (EmployeeDeparment filteredEmployeeDeparment : Iterables.filter(dep, predicate)) {
    ....
}

答案 1 :(得分:0)

Set<EmployeeDeparment> dep = p.getRequestEmpId().getEmpdep();       
if (!dep.isEmpty()) 
{
    for (EmployeeDeparment employeeDeparment : dep) 
    {
       if (employeeDeparment.isPrimarydept() == true && employeeDeparment.isStatus() == true) 
       {
           System.out.println("inside the employeedep");
           leaveRequestForm.setApprovalauthority(employeeDeparment.getReportingTo().getFirstname() + "" + employeeDeparment.getReportingTo().getLastname());
       }
    }
}
else 
{
    leaveRequestForm.setApprovalauthority("Approvalauthority not Configured");
}

可以替换为

Set<EmployeeDeparment> dep = p.getRequestEmpId().getEmpdep();       
if (!dep.isEmpty()) 
{
    dep.stream()
       .filter((employeeDeparment) -> employeeDeparment.isPrimarydept() == true && employeeDeparment.isStatus() == true)
       .forEach((x) -> 
       {
           System.out.println("inside the employeedep");
           leaveRequestForm.setApprovalauthority(employeeDeparment.getReportingTo().getFirstname() + "" + employeeDeparment.getReportingTo().getLastname());
       });
}
else
{
    leaveRequestForm.setApprovalauthority("Approvalauthority not Configured");
}