简体   繁体   中英

Iterator with starting point in iterator within treeset

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM