How to manipulate iterator position

Asked

Viewed 247 times

1

I need to compare all the elements of a list 2 a 2 am doing as follows:

List: 1, 2, 3, 4.

Comparison: 1 and 2, 1 and 3, 1 and 4, 2 and 1, 2 and 3...

I’m using it as follows:

    Iterator<Policie> p1Iterator = setOfPolicies.iterator();
    Iterator<Policie> p2Iterator;

    while(p1Iterator.hasNext()) {
        p1 = p1Iterator.next();
        count++;
        p2Iterator = setOfPolicies.iterator();

        while(p2Iterator.hasNext()) {
            p2 = p2Iterator.next();
        }
   }

What I wanted to stop doing, is to compare for example: 1 and 2 & 2 and 1. Since it is the same for me. So since I compare the first with all the others, the second with all the others... The second time, for example, I would compare the second with everyone in front of it, the third with everyone in front of it, and so on. The problem is I can’t manipulate the positions with the iterator, which I could do?

1 answer

4


Must necessarily be iterators?

You could convert to a list and so interact with the list positions.

You can use the library Guava: (best performance)

import com.google.common.collect.Lists;

List<Policie> policies = Lists.newArrayList(p1Iterator);

Or the library of java itself

import org.apache.commons.collections.IteratorUtils;

List<Policie> policies = IteratorUtils.toList(p1Iterator);

Or should it be mandatory with iterators? Using iterators will give a little more work.

Need to post comparison logic too?

  • It does not need to be with Iterator no, I did not know this method. I think so can solve, I will try here. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.