[英]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.