Make iterators cloneable?

Tagir F. Valeev amaembo at
Sun Sep 11 12:02:12 UTC 2016


As your keys are comparable, you can create normal iterators and
filter the results like this:

for(String v1 : s) {
  for(String v2 : s) {
    if(v1.compareTo(v2) < 0) {
      System.out.println(v1 + " <-->" + v2);

Or using Stream API: ->
    .filter(v2 -> v1.compareTo(v2) < 0).map(v2 -> v1 + " <-->" + v2))

With best regards,
Tagir Valeev.

DB> It would be nice to be able to associate each element in a collection 
DB> with another element in the collection, which is something very easily
DB> done with index based collections, but with sets, etc this isn't so 
DB> easy... unless i'm having a brainfart.

DB> So i'd like to do this, but Iterator doesn't implement Cloneable... Any
DB> reason not to? or is there another way that's missing me?

DB> public class ItClone {

DB>      public static void main(String[] args) {
DB>          Set<String> s = Collections.newSetFromMap(new 
DB> ConcurrentHashMap<String, Boolean>());

DB>          s.add("Fee");
DB>          s.add("Fi");
DB>          s.add("Fo");
DB>          s.add("Fum");

DB>          Iterator<String> it1 = s.iterator();
DB>          while (it1.hasNext()) {
DB>              String v1 =;

DB>              Iterator<String> it2 = (Iterator<String>) it1.*clone*();
DB>              while (it2.hasNext()) {
DB>                  String v2 =;

DB>                  System.out.println(v1 + " <-->" + v2);
DB>              }
DB>          }
DB>      }
DB> }

More information about the core-libs-dev mailing list