簡體   English   中英

使用Lambda進行代碼重構-Java 8

[英]Code refactoring using lambda - Java 8

我只是在研究函數式編程的基礎。 我想在Java中使用lambda轉換以下代碼。 我正在使用Java8。將不勝感激。

謝謝。

        String reinBranches = (String) application.getAttribute("xx_xx_xx");

    if(reinBranches != null && reinBranches.length() > 0)
    {
        String reinBranchArray[] = reinBranches.split(",");
        for(int i = 0; i < reinBranchArray.length; i++)
        {
            if(reinBranchArray[i].equals((String) session.getAttribute("xyz_xyz_xyz"))) {
                return true;
            }
        }
    }
    return false;

首先,我要獲取要匹配的屬性並將其保存(在lambda之前)。 然后從split stream處理String[] ,如果anyMatch條件則返回true 最后,使用邏輯和防止NPE return 喜歡,

String reinBranches = (String) application.getAttribute("xx_xx_xx");
String xyz3 = (String) session.getAttribute("xyz_xyz_xyz");
return reinBranches != null && Arrays.stream(reinBranches.split(",")).anyMatch(xyz3::equals);

如使用Pattern.splitAsStream的注釋中所建議的那樣,如果找到匹配項而不會從拆分中建立數組,則可以短路

return reinBranches != null && Pattern.compile(",").splitAsStream(reinBranches).anyMatch(xyz3::equals);

魔法

BooleanSupplier r = () -> {
    String reinBranches = (String) application.getAttribute("xx_xx_xx");

    if(reinBranches != null && reinBranches.length() > 0)
    {
        String reinBranchArray[] = reinBranches.split(",");
        for(int i = 0; i < reinBranchArray.length; i++)
        {
            if(reinBranchArray[i].equals((String) session.getAttribute("xyz_xyz_xyz"))) {
                return true;
            }
        }
    }
    return false;
}

這樣做的另一種方式而沒有使用流的任何開銷:-

String reinBranches = (String) application.getAttribute("xx_xx_xx");
String xyz3 = (String) session.getAttribute("xyz_xyz_xyz");

return reinBranches != null && Pattern.compile(xyz3).matcher(reinBranches).find(0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM