繁体   English   中英

如何用 Java 8 Streams 重写 For 循环和 If 语句

[英]How to rewrite For-loop and If-statement with Java 8 Streams

*我的代码:重写

final List<Employee> empList= getEmployeeList();
String empid = "1234";
Employee selectedEmp = new Employee();

for (Employee e1: empList) {
    if (empid .equals(e1.getEmpid()))
        selectedEmp = e1;
    }
}

现在我想在 Java 8 中重新连接上述代码。

我尝试了以下方法,但并非没有成功。 我不知道翻译if语句:

empList.stream()
    .foreach( <how to apply if condition here>)

forEach()在这里不是合适的工具。

Firstly there's a method Iterable.forEach() which you can invoke directly on a list without creating a stream, Stream.forEach() is not encouraged to be used in such a way by the Stream API documentation , it should be used with care如果您没有其他适合该任务的工具。

相反,您可以使用组合filter() + findFirst() ,它会产生 Optional 类型的结果。

要为未找到员工的情况提供默认值(例如在您的代码中通过无参数构造函数创建的虚拟Employee object ),您可以使用Optional.orElseGet()期望仅在需要时应用的Supplier当可选为空时)。

public Employee findEmployee(String empid) {
    
    return getEmployeeList().stream()
        .filter(e -> empid.equals(e.getEmpid()))
        .findFirst()
        .orElseGet(Employee::new);
}

我强烈建议您熟悉有关lambda 表达式的这些教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM