1
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()); } } ``` |
2
deepsleep 2014-08-03 12:54:29 +08:00 1
个人觉得不用再优化了,原来那样就可以了。
|
3
incompatible 2014-08-03 13:16:35 +08:00 1
楼主这个没法优化了吧 有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 } ``` |
4
coldear 2014-08-03 13:17:55 +08:00
不用再优化+1
|
5
andybest OP @incompatible 谢谢,这个 OOP 做的很好,自愧不如! :)
|
6
watzds 2014-08-03 19:52:22 +08:00 1
List<Deal> pendingDeals=new ArrayList<Deal>();
while(iterator.hasNext()){ pendingDeals.add(iterator.next()); if(!pendingDeals.isEmpty() && (pendingDeals.size()%10==0 || !iterator.hasNext())){ process(pendingDeals); } } |