我想优化我的代码,为此,我想通过地图并行迭代。
我目前的代码是:
for (String orderKey: insertMap.keySet()) {
if(orderKey.contains('#New')) {
//Do big stuff: (500 lines)
}
}
for (String orderKey: updateMap.keySet()) {
if(orderKey.contains('#New')) {
//Do same big stuff as above: (500 lines)
}
}
编辑:添加地图类型
Map<String,CustomObject> insertMap,updateMap = new Map<String,CustomObject>();
现在,正如您所见,内部IF
条件相同,只有orderKey
的值来自不同的地图。
orderKey
的值将与每个地图不同。他们永远不会是一样的。
有没有办法将这些FOR
循环合二为一?
也许像:
for((String orderKey : insertMap.keySet()) OR (String orderKey : udpateMap.keySet()))
{
if(orderKey.contains('#New')) {
//Do big stuff
}
}
我知道上面的代码是不可能的,我只想展示我在寻找的东西。
//Do Big Stuff
掩盖的行数几乎是500.因此我希望减少代码行。
非常感谢!
答案 0 :(得分:2)
在Java 8中,您可以使用Stream.concat
:
webix.ui({
cols:[
{
view:"tree",
id:"mytree",
tooltip:true,
data:tree_data,
select:true,
tooltip:{
template:"<span class='webix_strong'>Contenido: </span> #value#<br/>"
},
},
]
});
Google的Guava library已Iterables.concat
:
Stream.concat(insertMap.keySet().stream(), updateMap.keySet().stream())
.filter(orderKey -> orderKey.contains("#New"))
.forEach(orderKey -> {
...
});
当然,最“低技术”的方法是简单地提取方法:
for (String orderKey: Iterables.concat(insertMap.keySet(), updateMap.keySet())) {
...
}
答案 1 :(得分:1)
如果想要并行,首先将doStuff(key)函数提取到实现Runnable接口的类。
然后根据需要定义一个包含多个线程的线程池执行程序。您的for循环可能仍然存在,但不是调用您的函数,而是创建新类的实例并提交给您的执行者。