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));
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;
}
A
但是当然,如果迭代器返回的所有s都不是s,它会失败B
。
如果要过滤迭代器,请使用 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;
}
使用番石榴,以上可以简化为
return Sets.newHashSet(Iterators.filter(myFunc.iterator(), B.class));
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
}
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;
}
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());
}