投射Iterator的最佳方式< Object>到例如Set< String&gt [英] Best way to cast Iterator<Object> to a Set<String>, for instance

查看:106
本文介绍了投射Iterator的最佳方式< Object>到例如Set< String&gt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Iterator< Object> 转换为 Set< String>



最干净/最好的做法是什么?

解决方案

  public Set< B> getBs(){
Iterator< A> iterator = myFunc.iterator();
设置< B> result = new HashSet< B>();
while(iterator.hasNext()){
result.add((B)iterator.next();
}
返回结果;
}

但当然,如果所有 A 如果你想过滤迭代器,那么使用instanceof:如果你想过滤迭代器,那么使用instanceof:

  public Set  getBs(){
Iterator< A> iterator = myFunc.iterator();
Set< B> result = new HashSet< B>();
while(iterator.hasNext()){
A a = iterator.next();
if(a B){
result.add((B)iterator.next();
}
}
返回结果;
}

使用番石榴,以上可以减少到

  return Sets.newHashSet(Iterators.filter(myFunc.iterator(),B.class)); 


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

这篇关于投射Iterator的最佳方式&lt; Object&gt;到例如Set&lt; String&gt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆