Search code examples
javajava-8coding-stylerefactoring

Converting code in Java 8 streams


Is there any easy way to convert this code into java 8 using streams and forEach.

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));
} 

I tried to do something like

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));
});

but then I cannot use totalPages and statementsInEnvelope within ForEach, they cannot be accessed from the forEach scope
Lastly is there any cleaner way to refactor this thing. Any ideas would be appreciated.


Solution

  • The simplest solution is to use 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));
    });