Casting an Iterator<Object>
to a Set<String>
What would be the cleanest/best practice way?
Set iterator() method in Java with Examplesutil. Set. iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With