0

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.

randomuser1
  • 2,733
  • 6
  • 32
  • 68
  • The question is a bit hard to understand, at least for me. Could you give an example of such a list and what you'd like to do to it? – Mureinik Dec 17 '18 at 19:07
  • any specific reason you're using a `LinkedList` as opposed to an `ArrayList`?. in almost all cases one would favour the latter. – Ousmane D. Dec 17 '18 at 19:09

3 Answers3

2

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;
   }
}
miskender
  • 7,460
  • 1
  • 19
  • 23
0

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;
}
}
Eugen
  • 877
  • 6
  • 16
0

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
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126