Reputation: 1009
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?
Upvotes: 6
Views: 23821
Reputation: 85779
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...
}
}
Upvotes: 19
Reputation: 10613
Keep track of what the last element was manually.
Transaction last = null;
for (Transaction transaction : transactions) {
if (transaction.equals(targetTransaction)) {
System.out.println("Previous transaction: " + last);
}
last = transaction;
}
Upvotes: 1
Reputation: 9270
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;
}
Upvotes: 1