Reputation: 2803
I have a LinkedList
of objects in Java
and I want to iterate through it, and when I find a specific object there - I want to take the next object (the one that is right next to the first one).
I thought this would solve the case:
listIterator = items.listIterator();
while (listIterator.hasNext() && listIterator.previous().getCode().equals(search.getCurrentCode())) {
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
but I'm getting error:
java.util.NoSuchElementException: null
I think it's because of using .previous
, but I don't know how to handle that correctly, how could I solve it then? I'm using previous
, but what I want is to use the current element - I thought that's handled by .previous
, but apparently it's not.
Upvotes: 0
Views: 230
Reputation: 56433
First, I'd suggest using an ArrayList
instead of LinkedList
as the former is almost always the better option to use. see this post for more information.
You could definitely do this via a typical for loop or enhanced for loop, but I'd like to illustrate a new method as of JDK9 called dropWhile
which can help you accomplish this requirement of yours:
Assuming, you have your ArrayList
in place. you could simply do:
myList.stream()
.dropWhile(c -> !c.getCode().equals(search.getCurrentCode()))
.skip(1) // get the object to the right of the matched item
.findFirst() // retrieve this object
.ifPresent(s -> result.setCurrentCode(s.getCode())); // apply the logic based on the found object
Upvotes: 0
Reputation: 917
Try this:
listIterator = items.listIterator();
// listIterator.previous() does not exist in first iteration
while (listIterator.hasNext()) {
// you can compare previous value if it exist
if(listIterator.hasPrevious() && listIterator.previous().getCode().equals(search.getCurrentCode())){
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
}
Upvotes: 0
Reputation: 7958
Your current code fails because You are calling previous, before even start iterating on items. Iteration is done with listIterator.next();
call.
You can try the code below.
while (listIterator.hasNext()){
// iterate always
item = listIterator.next();
// if found and an element still exist
if(item.getCode().equals(search.getCurrentCode() && listIterator.hasNext()){
// get the next element
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
}
Upvotes: 2