Super-lazy Java solution using streams


  • 0
    W
    public class NestedIterator implements Iterator<Integer> {
    
        private final Iterator<Integer> iterator;
    
        private Stream<Integer> stream(NestedInteger nestedInteger) {
        return nestedInteger.isInteger() ? Stream.of(nestedInteger.getInteger()) : nestedInteger.getList().stream().flatMap(this::stream);
        }
    
        public NestedIterator(List<NestedInteger> nestedList) {
            iterator = nestedList.stream().flatMap(this::stream).iterator();
        }
    
        @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.