Search code examples
javadictionaryjava-8java-stream

Java stream an array list and compare with previous record


I have a simple RecordA class that holds an id and an int value. Multiple "sorted" RecordA elements are stored in a list.

I want to traverse the list and compare the current with the previous element and find the diff of their values.

Code:

import java.util.*;  

class RecordA{
    Integer id;
    Integer value;
    
    RecordA(Integer id, Integer value) {
        this.id = id;
        this.value = value;
    }
    
    Integer getId() { return id;}
    Integer getValue() { return value;}
}

class RecordB {
    Integer id;
    Integer value;
    Integer diff;
    
    RecordB(Integer id, Integer value, Integer diff) {
        this.id = id;
        this.value = value;
        this.diff = diff;
    }
    
    Integer getId() { return id;}
    Integer getValue() { return value;}
    Integer getDiff() { return diff;}
}

class HelloWorld {
    public static void main(String[] args) {
        
        
        List<RecordA> listA = new ArrayList<>();
        RecordA recordA1 = new RecordA(1,10);
        listA.add(recordA1);
        RecordA recordA2 = new RecordA(2,15);
        listA.add(recordA2);
        RecordA recordA3 = new RecordA(3,25);
        listA.add(recordA3);
        RecordA recordA4 = new RecordA(4,30);
        listA.add(recordA4);
        
        System.out.println(listA.size());
    }
}

I want using streams (if possible) to compare the current RecordA.value with the previous RecordA.value map the result into a RecordB with the same id and value, but store the current-previous.

At the end the List of RecordB will contain

  • 1, 10, 0 //(10-0)
  • 2, 15, 5 //(15-10)
  • 3, 25, 10 //25-15
  • 4, 30, 5 //30-25

I would like to avoid the class for loop and the previous_val variable. Any ideas how to do this with streams?


Solution

  • You could use IntStream

    IntStream.range(0, listA.size())
        .map(index -> 
            new RecordB(listA.get(index).getId(), listA.get(index).getValue(),  listA.get(index).getValue() - (index > 0 ? listA.get(index - 1).getValue() : 0))
        )
        .collect(Collectors.toList())