这个代码逻辑怎么优化?

2014-08-03 11:10:46 +08:00
 andybest
一个 iterator 每次产生一个 deal,我打算攒 10 个 deal 进行一次处理,现在的问题是因为无法判断最后一次next() 导致处理程序要写两遍:

List<Deal> pendingDeals=new ArrayList<Deal>();
while(iterator.hasNext()){
  pendingDeals.add(iterator.next());
  if(!pendingDeals.isEmpty()pendingDeals.size()%10==0){
    process(pendingDeals);
  }
}
//这里非常纠结,是否可以优化?
if(!pendingDeals.isEmpty()){
  process(pendingDeals);
}
2763 次点击
所在节点    问与答
6 条回复
kalasoo
2014-08-03 12:14:25 +08:00
```
while(true) {
if (iterator.hasNext()) {
pendingDeals.add(iterator.next());
if (!pendingDeals.isEmpty() && pendingDeals.size() == 10) {
process(pendingDeals);
}
} else {
if (!pendingDeals.isEmpty()) {
process(pendingDeals);
}
break;
}
}
```
或者

```
var end = false; //对不起啊,我Java写的不好,我就把逻辑先放在这里
while(true){
end = !iterator.hasNext();
if ((end || pendingDeals.size() == 10) && !pendingDeals.isEmpty()) {
process(pendingDeals);
}
if (end) {
break;
} else {
pendingDeals.add(iterator.next());
}
}
```
deepsleep
2014-08-03 12:54:29 +08:00
个人觉得不用再优化了,原来那样就可以了。
incompatible
2014-08-03 13:16:35 +08:00
楼主这个没法优化了吧 有buffer就要有flush
类比一下:你用OutputStream做了若干write操作,最后总得flush()一下


ps:
你得这么写才像java

```
DealProcessor p = new DealProcessorImpl();

while(iterator.hasNext()){
  p.process(iterator.next);
}

p.flush();
```


```
interface DealProcessor {
public void process(Deal deal);
public void flush();
}
```

```
class DealProcessorImpl {
private final static int BATCH_SIZE = 10;
private List<Deal> dealList = new ArrayList<Deal>();

public void process(Deal deal) {
dealList.add(deal);
if (dealList.size() == BATCH_SIZE) {
process(dealList):
dealList.clear();
}
}

public void flush() {
if (dealList.size() > 0) {
process(dealList):
dealList.clear();
}
}

protected void process(List<Deal> batch) {
// add your implementation here
}
```
coldear
2014-08-03 13:17:55 +08:00
不用再优化+1
andybest
2014-08-03 13:48:54 +08:00
@incompatible 谢谢,这个 OOP 做的很好,自愧不如! :)
watzds
2014-08-03 19:52:22 +08:00
List<Deal> pendingDeals=new ArrayList<Deal>();
while(iterator.hasNext()){
  pendingDeals.add(iterator.next());
  if(!pendingDeals.isEmpty() && (pendingDeals.size()%10==0 || !iterator.hasNext())){
    process(pendingDeals);
  }
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/125857

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX