簡體   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