Interview: Design an iterator for a collection of collections

前端 未结 6 1100
Happy的楠姐
Happy的楠姐 2020-12-29 12:09

Design an iterator for a collection of collections in java. The iterator should hide the nesting, allowing you to iterate all of the elements belonging to all of the collect

6条回答
  •  渐次进展
    2020-12-29 12:33

    This is an old question, but nowadays (2019) we have JDK8+ goodies. In particular, we have streams, which make this task straightforward:

    public static  Iterator flatIterator(Collection> collections) {
    
        return collections.stream()
                .filter(Objects::nonNull)
                .flatMap(Collection::stream)
                .iterator();
    }
    

    I'm filtering null inner collections out, just in case...


    EDIT: If you also want to filter null elements out of the inner collections, just add an extra non-null filter aflter flatMap:

    return collections.stream()
            .filter(Objects::nonNull)
            .flatMap(Collection::stream)
            .filter(Objects::nonNull)
            .iterator();
    

提交回复
热议问题