【问题标题】:How to implement iterator on nested collection in Java?如何在 Java 中的嵌套集合上实现迭代器?
【发布时间】:2013-10-10 10:17:22
【问题描述】:

我有一个嵌套集合,这个表示Collection<Collection<T>>。我已经在类上实现了迭代器,但是 next() 方法没有给出正确的结果。它只获取每个列表的第一个元素。示例 List<List<String>> 和值为 {"1","2"},{"3","4"},{"5","6"}。类的完整布局。

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class NestedCollectionIterator implements Iterator<Object> {

private  Collection<? extends Collection<? extends Object>> _collOfColl = null;
private Iterator<? extends Collection<? extends Object>> itCollection = null;
private Iterator<? extends Object> innerIterator = null;    
Object next = null;

public NestedCollectionIterator( Collection<? extends Collection<? extends  Object>> collofColl){
    _collOfColl = collofColl;   
    itCollection = _collOfColl.iterator();
}

@Override
public boolean hasNext() {
    if(itCollection.hasNext()){
        innerIterator = itCollection.next().iterator();
        if(innerIterator != null || innerIterator.hasNext()){
            next = innerIterator.next();
            return true;
        }
    }
    return false;
}

public Object next() {
    if(hasNext()){
      Object obj = next;
     //Need some changes here.
       return obj;
    }
    return null;
}

@Override
public void remove() {}

}

测试实现的类

class Sample{
public static void main(String[] args){
    List<List<String>> Nestedlist = new ArrayList<List<String>>();
    List<String> l = new ArrayList<String>();
    l.add("1");
    l.add("2");
    Nestedlist.add(l);
    l = new ArrayList<String>();
    l.add("3");
    l.add("4");
    Nestedlist.add(l);
    l = new ArrayList<String>();
    l.add("5");
    l.add("6");
    Nestedlist.add(l);

    NestedCollectionIterator cc = new NestedCollectionIterator(Nestedlist);

    while(cc.hasNext()){
        System.out.println(cc.next.toString());
    }
  }
}

结果是 1,3,5。如何让列表先遍历列表中的所有元素,然后移动到其中的下一个集合项?

谢谢。

【问题讨论】:

  • 目前你对Iterator 接口的“实现”只是说你没有任何元素。你试过什么,发生了什么? (“没有给出正确的结果”是不够的信息。)
  • 你有多少关卡?只有 1 个?
  • 好吧,return null; 似乎不对,我同意。但问题是什么? I tried to implement 请加倍努力,因为只是添加了一些字段,否则将生成的方法保持原样并没有太多“实现”...
  • 如果您发布代码(以及足够详细地描述问题)并且我们会告诉您您做错了什么,而不是我们只是从头开始提供解决方案,您将学到更多。这也恰好是Stack Overflow 问题所必需的。
  • 我已经更新了代码和问题。请检查

标签: java loops collections iterator


【解决方案1】:

这个对我有用 - 它没有推广到 Collection,但有一些实用方法可以为您提供一个迭代器迭代器,最多可以跨越三个级别的 Map。我相信您可以将其调整为一般的集合。

public class NestedIterator<T> implements Iterator<T> {
  // Outer iterator. Goes null when exhausted.
  Iterator<Iterator<T>> i2 = null;
  // Inner iterator. Goes null when exhausted.
  Iterator<T> i1 = null;
  // Next value.
  T next = null;

  // Takes a depth-2 iterator.
  public NestedIterator(Iterator<Iterator<T>> i2) {
    this.i2 = i2;
    // Prime the pump.
    if (i2 != null && i2.hasNext()) {
      i1 = i2.next();
    }
  }

  @Override
  public boolean hasNext() {
    // Is there one waiting?
    if (next == null) {
      // No!
      // i1 will go null if it is exhausted.
      if (i1 == null) {
        // i1 is exhausted! Get a new one from i2.
        if (i2 != null && i2.hasNext()) {
          /// Get next.
          i1 = i2.next();
          // Set i2 null if exhausted.
          if (!i2.hasNext()) {
            // Exhausted.
            i2 = null;
          }
        } else {
          // Exhausted.
          i2 = null;
        }
      }
      // A null i1 now will mean all is over!
      if (i1 != null) {
        if (i1.hasNext()) {
          // get next.
          next = i1.next();
          // Set i1 null if exhausted.
          if (!i1.hasNext()) {
            // Exhausted.
            i1 = null;
          }
        } else {
          // Exhausted.
          i1 = null;
        }
      }
    }
    return next != null;
  }

  @Override
  public T next() {
    T n = next;
    next = null;
    return n;
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException("Not supported.");
  }

  // Iterating across Maps of Maps of Maps.
  static <K1, K2, K3, V> Iterator<Iterator<Iterator<V>>> iiiV(Map<K1, Map<K2, Map<K3, V>>> mapMapMap) {
    final Iterator<Map<K2, Map<K3, V>>> mmi = iV(mapMapMap);
    return new Iterator<Iterator<Iterator<V>>>() {
      @Override
      public boolean hasNext() {
        return mmi.hasNext();
      }

      @Override
      public Iterator<Iterator<V>> next() {
        return iiV(mmi.next());
      }

      @Override
      public void remove() {
        mmi.remove();
      }
    };
  }

  // Iterating across Maps of Maps.
  static <K1, K2, V> Iterator<Iterator<V>> iiV(Map<K1, Map<K2, V>> mapMap) {
    final Iterator<Map<K2, V>> mi = iV(mapMap);
    return new Iterator<Iterator<V>>() {
      @Override
      public boolean hasNext() {
        return mi.hasNext();
      }

      @Override
      public Iterator<V> next() {
        return iV(mi.next());
      }

      @Override
      public void remove() {
        mi.remove();
      }
    };
  }

  // Iterating across Map values.
  static <K, V> Iterator<V> iV(final Map<K, V> map) {
    return iV(map.entrySet().iterator());
  }

  // Iterating across Map.Entries.
  static <K, V> Iterator<V> iV(final Iterator<Map.Entry<K, V>> mei) {
    return new Iterator<V>() {
      @Override
      public boolean hasNext() {
        return mei.hasNext();
      }

      @Override
      public V next() {
        return mei.next().getValue();
      }

      @Override
      public void remove() {
        mei.remove();
      }
    };
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2020-10-22
    • 2017-12-08
    相关资源
    最近更新 更多