title: Find and return an element from a TreeSet in Java
body: <p>I have the following Node Class</p>
  
  <pre><code>Class Node {
      private int id;
  
      public int getId() {
          return this.id;
      }
  }
  </code></pre>
  
  <p>and then create a TreeSet with the Nodes. Next I wanted to find and return a Node object based on id matching. However, every time the findNode() function is returning the next-to-next Node not the next one. I understand it is because of calling the iterator.next() twice. How can call it only once to check with the id value as well as return the object reference. I also tried with by creating a temporary Object reference but again it was the same result.</p>
  
  <pre><code>Class NodeSet {
      Set&lt;Node&gt; set = new TreeSet&lt;Node&gt;();
  
      public Node findNode(int id) {  
          Iterator&lt;Node&gt; iterator = set.iterator();
          while(iterator.hasNext()) {
              if(iterator.next().getId() == id)               
                  return iterator.next();
          }
  
          return null;                
      }
  }
  </code></pre>