Omen Omen - 5 months ago 15
Java Question

Get all possible pairs of elements in a TreeSet

Let's say I have a TreeSet of objects x. What I am trying to do, is iterate through all objects and get all possible pairs. So far, I have come to the code below

TreeSet<x> ts = new TreeSet<>();
ts.add(new x(3, true));
ts.add(new x(1, true));
ts.add(new x(2, true));
ts.add(new x(5, true));
ts.add(new x(4, true));
Iterator<x> iterator = setOfX.iterator();
while (iterator.hasNext()) {
System.out.println("ID:"+iterator.next());
Iterator<x> innerIterator = setOfX.tailSet(iterator.next(), true).iterator();
while (innerIterator.hasNext()) {
int id = innerIterator.next().id;
System.out.println(id);
}
}


But the output seems to luck some of the combinations, plus it exits with an exception

ID:1:true
2
3
4
5
ID:3:true
4
5
ID:5:true
Exception in thread "main" java.util.NoSuchElementException


Can you point towards any solution?

Answer

The problem is that you are calling iterator.next() two times. Note that this method not only gets what the iterator is currently pointing at, it also advances the iterator to the next element. Call iterator.next() only once per iteration and store its return value in a variable:

TreeSet<x> ts = new TreeSet<>();
ts.add(new x(3, true));
ts.add(new x(1, true));
ts.add(new x(2, true));
ts.add(new x(5, true));
ts.add(new x(4, true));
Iterator<x> iterator = setOfX.iterator();
    while (iterator.hasNext()) {
        // Call iterator.next() only once per iteration
        x value = iterator.next();

        System.out.println("ID:"+value);
        Iterator<x> innerIterator = setOfX.tailSet(value, true).iterator();
        while (innerIterator.hasNext()) {
            int id = innerIterator.next().id;
            System.out.println(id);
        }
    }