Find and return an element from a TreeSet in Java
java
Solution
Class NodeSet {
Set<Node> set = new TreeSet<Node>();
public Node findNode(int id) {
Iterator<Node> iterator = set.iterator();
while(iterator.hasNext()) {
Node node = iterator.next();
if(node.getId() == id)
return node;
}
return null;
}
}
Problem
I have the following Node Class ``` Class Node { private int id; public int getId() { return this.id; } } ``` 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. ``` Class NodeSet { Set<Node> set = new TreeSet<Node>(); public Node findNode(int id) { Iterator<Node> iterator = set.iterator(); while(iterator.hasNext()) { if(iterator.next().getId() == id) return iterator.next(); } return null; } } ```