Best way to cast Iterator<Object> to a Set<String>, for instance

27,785

Solution 1

public Set<B> getBs(){
    Iterator<A> iterator = myFunc.iterator();
    Set<B> result = new HashSet<B>();
    while (iterator.hasNext()) {
        result.add((B) iterator.next();
    }
    return result;
}

But of course, it will fail if all the As returned by the iterator are not Bs.

If you want to filter the iterator, then use instanceof:

public Set<B> getBs(){
    Iterator<A> iterator = myFunc.iterator();
    Set<B> result = new HashSet<B>();
    while (iterator.hasNext()) {
        A a = iterator.next();
        if (a instanceof B) {
            result.add((B) iterator.next();
        }
    }
    return result;
}

Using Guava, the above can be reduced to

return Sets.newHashSet(Iterators.filter(myFunc.iterator(), B.class));

Solution 2

If we are talking about iterators and collections that need to use them, and you need the iterater to be generic enough so that it can be used by different collections.
Just use if/else with instanceof keyword as follows:

while(iterator.hasNext()) {
  Object obj = iterator.next();
  if (obj instanceof A) {
    collection.add((A) o);  
  } else if (obj instanceof B) {
    collection.add((B) o);  
  } else if ...etc
}

Solution 3

I'm still not 100% sure what you want, but check this out and see:

public static void main(String[] args) {
  final Iterator<?> it = Arrays.asList(new Object[] {"a", "b", "c"}).iterator();
  System.out.println(setFromIterator(it));
}

public static Set<String> setFromIterator(Iterator<?> it) {
  final Set<String> s = new HashSet<String>();
  while (it.hasNext()) s.add(it.next().toString());
  return s;
}

Solution 4

That's the only way, probably.

while(iterator.hasNext()) {
  Object o = iterator.next();
  if (o instanceof B) {
    collection.add((B) o);  
  }
}

Solution 5

org.apache.commons.collections.IteratorUtils can be used to do this.

Here is an example to convert iterator to set;

Set<String> mySet = new HashSet<String>(IteratorUtils.toList(myIterator))
Share:
27,785
Whimusical
Author by

Whimusical

Half of the time we're gone but we don't know where...

Updated on August 03, 2020

Comments

  • Whimusical
    Whimusical almost 4 years

    Casting an Iterator<Object> to a Set<String>

    What would be the cleanest/best practice way?