I am using a LinkedList and I want to get the previous (and the next) element, but not sure how to approach that.
My linked list:
LinkedList<Transaction> transactions = transactionRepository.findAll();
I am searching for this transaction:
Transaction targetTransaction = new Transaction("admin", new Date(), 5);
What I want to do:
for (Transaction transaction : transactions) {
    if (transaction.equals(targetTransaction)) {
        System.out.println("Previous transaction: " + transaction.getPrev());
    }
}
The transaction.getPrev() part does not work, because my Transaction object does not have such method.
Question: how to correctly obtain the "previous" object from the LinkedList?
Enhanced for loop uses Iterator behind the scenes, and this interface doesn't provide any method to go to the previous element. Use LinkedList#listIterator instead:
ListIterator<Transaction> li = transactions.listIterator(0);
while (li.hasNext()) {
    //your logic goes here
    //if you need to go to the previous place
    if (li.hasPrevious()) {
        li.previous();
        //further logic here...
    }
}
                        Keep track of the previous Transaction as you go through the list.
Transaction prev = null;
for (Transaction transaction : transactions) {
    if (transaction.equals(targetTransaction)) {
        System.out.println("Previous transaction: " + (prev = null ? "[none]" : prev));
    }
    prev = transaction;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With