By kswaughs | Tuesday, May 5, 2020

How to get previous or next item of list in Java using Streams

Basically Java Streams does not provide any in-built operators to get previous or next item while processing current item of the list.

But we can achieve this by using reduce operator properly as per our needs.

In this example, we have list of transactions and each transaction has 'id' and 'currentBalance' fields. Now we will populate 'previousBalance' field of each transaction from previous transaction object.
package com.kswaughs.example;

import java.util.ArrayList;
import java.util.List;

import com.kswaughs.model.Transaction;

public class TransactionExample {

    public static void main(String[] args) {
        List<Transaction> items = new ArrayList<>();
        items.add(new Transaction(1, 100.0));
        items.add(new Transaction(2, 200.0));
        items.add(new Transaction(3, 300.0));
        items.add(new Transaction(4, 400.0));,b) -> {
            return b;

Model class
package com.kswaughs.model;

public class Transaction {

    private int id;
    private double currentBalance;
    private double prviousBalance;
    public Transaction(int id, double currentBalance) { = id;
        this.currentBalance = currentBalance;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public double getCurrentBalance() {
        return currentBalance;

    public void setCurrentBalance(double currentBalance) {
        this.currentBalance = currentBalance;

    public double getPrviousBalance() {
        return prviousBalance;

    public void setPrviousBalance(double prviousBalance) {
        this.prviousBalance = prviousBalance;

    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Transaction [id=").append(id)
            .append(", currentBalance=").append(currentBalance)
            .append(", prviousBalance=").append(prviousBalance)
        return builder.toString();


[Transaction [id=1, currentBalance=100.0, prviousBalance=0.0]
, Transaction [id=2, currentBalance=200.0, prviousBalance=100.0]
, Transaction [id=3, currentBalance=300.0, prviousBalance=200.0]
, Transaction [id=4, currentBalance=400.0, prviousBalance=300.0]

Recommend this on

No comments:

Post a Comment