Omen
Omen

Reputation: 313

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?

Upvotes: 1

Views: 682

Answers (2)

Gaurava Agarwal
Gaurava Agarwal

Reputation: 974

You are doing iterator.next() two times. One inside sysout other when creating innerIterator.

    System.out.println("ID:"+iterator.next());

    Iterator<x> innerIterator = setOfX.tailSet(iterator.next(),true).iterator();

use next() once for each call of iterator.hasNext(), you will not have Exception.

Upvotes: 1

Jesper
Jesper

Reputation: 206876

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);
        }
    }

Upvotes: 2

Related Questions