Casting an Iterator<Object>
to a Set<String>
What would be the cleanest/best practice way?
Casting an Iterator<Object>
to a Set<String>
What would be the cleanest/best practice way?
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 A
s returned by the iterator are not B
s.
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));
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;
}
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
}
That's the only way, probably.
while(iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof B) {
collection.add((B) o);
}
}
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))
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());
}