我只是在研究函数式编程的基础知识。我想使用Java中的lambda来转换下面的代码。我正在使用java 8。任何帮助都将不胜感激。
谢谢。
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;发布于 2018-03-20 12:07:20
首先,我将获得要与之匹配的属性,并保存它(在lambda之前)。然后从您的stream中提取String[]并返回true,如果anyMatch是您的标准的话。最后,使用逻辑并防止return上的NPE。喜欢,
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);发布于 2018-03-20 12:05:36
魔术
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;
}发布于 2018-03-20 19:36:12
这只是另一种不使用任何流开销的方法:-
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);https://stackoverflow.com/questions/49383676
复制相似问题