Search code examples
javaiteratornested-loops

Java: Printing all unique unordered pairs with nested (quadratic) loop using iterator


The following code prints all unique unordered pairs of a given list.

//Input: List containing {a, b, c, d, e}
//Output: (a, b) (a, c) (a, d) (a, e) (b, c) (b, d) (b, e) (c, d) (c, e) (d, e)

private static void pairs(List<Character> list) {
    for (int i = 0; i < list.size()-1; i++){
        for (int j = i+1; j < list.size(); j++){
            System.out.print("("+list.get(i)+", "+list.get(j)+") ");
        }
    }
}

I want to do the same thing using iterators as using "get" would be really bad if the list is LinkedList. I'm having trouble with the j = i + 1 part. The code I'm looking for probably should look something like this.

private static void pairs2(List<Character> list) {
    Iterator<Character> iter1 = list.iterator();
    while(iter1.hasNext()){
        char char1 = iter1.next().charValue();
        Iterator<Character> iter2 = ???;
        while (iter2.hasNext()){
            char char2 = iter2.next().charValue();
            System.out.print("("+char1+", "+char2+") ");
        }
    }
}

Edit for future reference: As suggested bellow seems that the best way is to use ListIterator instead of Iterator.

ListIterator <Character> iter1 = list.listIterator();
...
ListIterator<Character> iter2 = list.listIterator(iter1.nextIndex());

Solution

  • If you use a ListIterator rather than a normal Iterator via list.listIterator(), you can get its index via iter1.nextIndex(). Then you can start iter2 as list.listIterator(index) from that position.