Best way to cast Iterator<Object> to a Set

2020-06-18 00:45发布

问题:

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

What would be the cleanest/best practice way?

回答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));


回答2:

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


回答3:

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
}


回答4:

That's the only way, probably.

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


回答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))


回答6:

You can not cast the Iterator to Set directly. Iterator pattern provides the way to access the elements of an aggregate object sequentially without exposing its underlying presentation. The possible solution is to travel each elements sequentially and add each element to the set

while (iterator.hasNext()) {
    Object obj = iterator.next();
    set.add(obj.toString());
}