title: How to iterate a list in both directions?
body: <p>I have a list of objects and want to iterate in forwards and backwards, until an element is found that is "valid".</p>
  
  <pre><code>MyClass {
      private boolean valid;
      public boolean isValid() { return valid; }
  }
  
  List&lt;MyClass&gt; classes; //assume sorted list
  </code></pre>
  
  <p>Now I want to start at position <code>idx</code>, and iterate both forwards and backwards to find the closest element that is valid. So far I already got the forward algorithm working. But I feel that the code could be optimized:</p>
  
  <p>//supposed to start at position X</p>
  
  <pre><code>int idx = 10;
  
  //find the closest element that is valid
  for (ListIterator&lt;MyClass&gt; itr = classes.listIterator(idx); itr.hasNext();) {
      if (itr.hasNext()) {
          MyClass my = itr.next();
          while (!my.isValid()) {
              if (itr.hasNext()) {
                  my = itr.next();
              } else {
                  break;
              }
          }
      }
      Sysout("the closest valid element is: " + my);
  }
  </code></pre>
  
  <p>Could the iterator algorithm be written better?</p>