Flattening a collection

前端 未结 9 2034
走了就别回头了
走了就别回头了 2020-11-30 02:55

Say I have a Map>

I can get the values of the map easily enough, and iterate over it to produce a single

9条回答
  •  粉色の甜心
    2020-11-30 03:24

    If you just want to iterate through values, you can avoid all these addAll methods.

    All you have to do is write a class that encapsulates your Map, and that implements the Iterator :

    public class ListMap implements Iterator
    {
      private final Map> _map;
      private Iterator>> _it1 = null;
      private Iterator _it2 = null;
    
      public ListMap(Map> map)
      {
        _map = map;
        _it1 = map.entrySet().iterator(); 
        nextList();
      }
    
      public boolean hasNext()
      {
        return _it2!=null && _it2.hasNext();
      }
    
      public V next()
      {
        if(_it2!=null && _it2.hasNext())
        {
          return _it2.next();
        }
        else
        {
          throw new NoSuchElementException();
        }
        nextList();
      } 
    
      public void remove()
      {
        throw new NotImplementedException();
      }
    
      private void nextList()
      {
        while(_it1.hasNext() && !_it2.hasNext())
        {
          _it2 = _it1.next().value();
        }
      }
    }
    

提交回复
热议问题