Java 8 using Streaming API


  • 1
    K
    public class NestedIterator implements Iterator<Integer> {
    
      private Iterator<Integer> iterator;
      
      public NestedIterator(List<NestedInteger> nestedList) {
        iterator = flatStream(nestedList).iterator();
      }
    
      private Stream<Integer> flatStream(List<NestedInteger> nestedList) {
        return nestedList.stream()
            .flatMap(ni -> ni.isInteger() ? Stream.of(ni.getInteger()) : flatStream(ni.getList()));
      }
    
      @Override
      public Integer next() {
        return iterator.next();
      }
    
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
    
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.