gpt4 book ai didi

java - 如何在嵌套 for 循环中重用用于 for 循环第一级的变量

转载 作者:行者123 更新时间:2023-12-01 20:51:20 26 4
gpt4 key购买 nike

有人可以告诉我如何在 forEach 中重用 rootOpt 对象。有什么办法可以重用这个变量吗?当我在 forEach 中写入 rootOpt.getChildOptions() 时,出现以下消息“无法解析符号 rootOpt”。请在下面找到我所做的:我尝试使用流重写下面的 for 循环。谢谢

opts.stream()
.flatMap(rootOpt -> rootOpt.getChildOptions().stream())
.forEach(subOpt -> {
if (subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant())) {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
for (String ch : oldCHs) {
Option chRootOpt = childOptCodeToParentOptMap.get(ch.toUpperCase());
if (chRootOpt != null) {
if (!DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions())) {
List<OptionList> tmp = new ArrayList<OptionList>();
tmp.add(samePriceSibs);
tmp.add(chRootOpt.getChildOptions());
optionsPairsToRemoveCHs.add(tmp);
}
}
}
}
});

for (Option rootOpt : opts) {
for (Option subOpt : rootOpt.getChildOptions()) {
if (subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant())) {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
for (String ch : oldCHs) {
Option chRootOpt = childOptCodeToParentOptMap.get(ch.toUpperCase());
if (chRootOpt != null) {
if (!DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions())) {
List<OptionList> tmp = new ArrayList<OptionList>();
tmp.add(samePriceSibs);
tmp.add(chRootOpt.getChildOptions());
optionsPairsToRemoveCHs.add(tmp);
}
}
}
}
}
}

最佳答案

rootOpt 的范围以右括号结束。你可以这样写

opts.stream().forEach(rootOpt ->
rootOpt.getChildOptions().stream().forEach(subOpt -> {
...
});
);

然而,流并不是真正旨在简单地替换 for 循环。使用它们的更规范的方式是这样的。

Stream<List<OptionList>> optionsPairsToRemoveCHs = opts.stream()
.flatMap(rootOpt ->
rootOpt.getChildOptions().stream()
.filter(subOpt -> subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant()))
.flatMap(subOpt -> {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
return Stream.of(oldCHs)
.map(ch -> childOptCodeToParentOptMap.get(ch.toUpperCase()))
.filter(chRootOpt -> chRootOpt != null && !DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions()))
.map(chRootOpt -> Arrays.asList(samePriceSibs, chRootOpt.getChildOptions()));
})
);

不过我没有测试该代码。另外,按照迈克的建议将其重构为几种方法将有助于使其更易于阅读。

关于java - 如何在嵌套 for 循环中重用用于 for 循环第一级的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43412331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com