Understanding Spliterator, Collector and Stream in Java 8

后端 未结 4 1008
栀梦
栀梦 2020-12-12 10:33

I am having trouble understanding the Stream interface in Java 8, especially where it has to do with the Spliterator and Collector interfaces. My problem is that I simply ca

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 11:16

    Interface Spliterator - is a core feature of Streams.

    The stream() and parallelStream() default methods are presented in the Collection interface. These methods use the Spliterator through the call to the spliterator():

    ...
    
    default Stream stream() {
        return StreamSupport.stream(spliterator(), false);
    }
    
    default Stream parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
    
    ...
    

    Spliterator is an internal iterator that breaks the stream into the smaller parts. These smaller parts can be processed in parallel.

    Among other methods, there are two most important to understand the Spliterator:

    • boolean tryAdvance(Consumer action) Unlike the Iterator, it tries to perform the operation with the next element. If operation executed successfully, the method returns true. Otherwise, returns false - that means that there is absence of element or end of the stream.

    • Spliterator trySplit() This method allows to split a set of data into a many smaller sets according to one or another criteria (file size, number of lines, etc).

提交回复
热议问题