有没有简单的方法可以使用streams和forEach将此代码转换为java 8。
List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
int totalPages = 0;
for(byte[] byteArray :byteArrays){
totalPages = totalPages + getPagesInDocument(byteArray);
if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
totalPages = 0;
listOfEnvelopes.add(statementsInEnvelope);
tatementsInEnvelope = new ArrayList<IStitchable>();
}
statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
}
我尝试做类似
的事情byteArrays.stream().forEach(byteArray->{
totalPages = totalPages + getPagesInDocument(byteArray);
if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
totalPages = 0;
listOfEnvelopes.add(statementsInEnvelope);
statementsInEnvelope = new ArrayList<IStitchable>();
}
statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});
但我不能在ForEach中使用totalPages
和statementsInEnvelope
,
无法从forEach范围访问它们
最后有没有更简洁的方法来重构这个东西。任何想法都将不胜感激。
答案 0 :(得分:1)
最简单的解决方案是使用AtomicInteger
:
List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
AtomicInteger totalPages = new AtomicInteger();
byteArrays.stream().forEach(byteArray -> {
totalPages.addAndGet(getPagesInDocument(byteArray));
if(totalPages.get() / 2 > MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
totalPages.set(0);
listOfEnvelopes.add(new ArrayList<>(statementsInEnvelope));
statementsInEnvelope.clear();
}
statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});