4

I have a TreeSet and iterate through it. When iterating through it I have to compare each element with the remaining entries in this TreeSet.

The problme is that I can't have an iterator which starts at a specific point.

TreeSet<Object> tree = new TreeSet<>();

Iterator<Object> i1= tree.iterator();
while (i1.hasNext()) {
    element1 = i1.next();

    ListIterator<String> i2 = // start at the point from 'i1'  
    while (i2.hasNext()) {
        element2  = i2.next();
        System.out.println("Interact: " + element1 + " " + element2  );
    }

}

I need the TreeSet because the inserting and sorting speed of it is perfect for what I do. I do need a solution without the use of a Libary.

How would you solve this?

arc
  • 4,553
  • 5
  • 34
  • 43
  • Don't use iterator, try with enhanced for loop or two for loops based on the treeset size. Complexity will take a hit though. You can also try converting the set toArray() and use that array. – Shaik Md Nov 03 '15 at 09:31
  • I'd like to use something other than an Iterator. The TreeSet contains about 10^5 entries, but they won't change when filled. I'll try converting it, haven't thought about it. – arc Nov 03 '15 at 09:42

1 Answers1

6

You can use tailSet(E fromElement, boolean inclusive) to get a sub-set starting at the required element and then iterate on that sub-set.

Iterator<Object> i1= tree.iterator();
while (i1.hasNext()) {
    element1 = i1.next();

    Iterator<Object> i2 = tree.tailSet(element1,true).iterator();
    while (i2.hasNext()) {
        element2  = i2.next();
        System.out.println("Interact: " + element1 + " " + element2  );
    }

}

As OldCurmudgeon mentioned can be simplified with

for (Object element1 : tree) { 
   for (Object element2 : tree.tailSet(o, true)) { 
       System.out.println("Interact: " + element1 + " " + element2  );
   } 
}
arc
  • 4,553
  • 5
  • 34
  • 43
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 4
    Can be greatly simplified with `for (Object o : tree) { for (Object p : tree.tailSet(o, true)) { } }` – OldCurmudgeon Nov 03 '15 at 09:43
  • Will this copy part of the TreeSet or other put how expensive is this operation? The TreeSet contains about 10^5 entires and I'd have to do it a lot. – arc Nov 03 '15 at 09:45
  • 1
    @Omix22 According to the Javadoc, `tailSet` `Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement. The returned set is backed by this set`. This means it doesn't create a copy of the original Set. – Eran Nov 03 '15 at 09:48