Best way to throw Iterator <Object> into Set <String>, for example

Listing Iterator<Object>onSet<String>

What will be the cleanest / best way?

+5
source share
6 answers
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 not work if all Areturned by the iterator are not Bs.

If you want to filter the iterator, 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));
+6
source

If we are talking about iteratorsand collectionswho should use them, and you need to iteraterbe general enough so that it can be used differently collections.
Just use if/elsewith the keyword instanceofas 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
}
+3

100%, , :

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

, .

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

org.apache.commons.collections.IteratorUtils can be used for this.

Here is an example to convert an iterator to install;

Set<String> mySet = new HashSet<String>(IteratorUtils.toList(myIterator))
+1
source

You cannot use Iterator to install directly. The Iterator template provides the ability to access the elements of an aggregate object sequentially without exposing it to the main presentation. Possible solution: move each element sequentially and add each element to the set

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

All Articles