java Stream operation

Four built-in core functional interfaces in Java 8

Consumer < T >: consumer interface
		void accept(T t);
Supplier < T >: supply type interface
		T get();
Function < T, R >: functional interface
		R apply(T t);
Predicate < T >: predicate interface
		boolean test(T t);

Create Stream

1. steam() or parallelStream() provided by Collection Series Collection
List<String> list = new ArrayList<>();
Stream<String> stream1 =;
2. The static method stream() of array gets the array stream
Employee[] emps = new Employee[10];
Stream<Employee> stream =;
3. Static method of stream class ()
Stream<String> stream = Stream.of("aa","bb","cc","dd");
4. Create an infinite stream
Stream<Integer> stream = Stream.iterate(0,x->x+2);

Intermediate operation of Stream

Multiple intermediate operations can be connected to form a pipeline. Unless the termination operation is triggered on the pipeline, the intermediate operation will not perform any processing! When the operation is terminated, it is processed all at once, which is called "lazy evaluation". That is, if the operation is not terminated, all intermediate operations will not be executed.

Screening and slicing

Filter: receive lambda and filter out some elements from the stream according to rules.
limit: truncate the stream so that its elements do not exceed the specified number. If there are not enough elements in the stream, an empty stream is returned.
Skip: skip the specified number of n elements and return the stream of the remaining elements. If there are less than n elements in the stream, an empty stream will be returned.
distinct: de duplication, removing duplicate elements through hashCode() and equals() of elements in the stream


map: the received lambda is applied to each element, and each element in the stream is mapped into a new element.
flatMap: change each element in the stream into a new stream, and then splice all streams into a stream, which is equivalent to dimensionality reduction operations, such as changing a two-dimensional array into a one-dimensional array.

// flatMap: take out the elements in the multi-layer collection and put them into a new collection
        List<Integer> num1 = Arrays.asList(1, 2, 3);
        List<Integer> num2 = Arrays.asList(4, 5, 6);
        List<Integer> num3 = Arrays.asList(7, 8, 9);
        List<List<Integer>> lists = Arrays.asList(num1, num2, num3);
        List<Integer> flatMapResult  = ->

sorted: natural sorting, by default.
sorted(Comparator c): sort according to the specified rule

Terminal operation

anyMatch means that in the judged condition, any element succeeds and returns true

allMatch indicates that all elements in the judgment condition are and return true

noneMatch is opposite to allMatch. All elements in the judgment condition are not and return true
findFirst returns the first element
findAny returns any element
count returns the number of elements in the stream
max returns the maximum value in the stream
min returns the minimum value in the stream

reduce: receive an aggregation algorithm for element summary


collect: convert the Stream into other forms and receive the implementation of a Collector interface, which is used to summarize the elements of the Stream

List<Integer> collect =;
        Set<Integer> collect1 =;
        Map<Integer, Double> collect2 =, Employee::getSalary));
        // Specifies the collection type
        HashSet<Integer> collect3 =;
         // Multilevel grouping
        Map<Double, Map<String, List<Employee>>> collect5 =, Collectors.groupingBy(e -> {
            if (e.getAge() < 20) {
                return "juvenile";
            } else if (e.getAge() < 50) {
                return "middle age";
            } else {
                return "old age";
        Map<Boolean, List<Employee>> collect7 = -> e.getAge() > 20));
        DoubleSummaryStatistics collect8 =;

// joining
        String collect9 =","));

Fork/Join framework and parallelStream

Fork/Join framework: when necessary, fork a large task into several small tasks (it should be noted that the granularity of the task should be reasonably selected, which is too large to improve efficiency through parallelism, and too small will waste resources on splitting tasks and increase additional expenses). After the task is split, Then, the demerit records of all subtask operations are joined and summarized.

In short, ForkJoin's core idea is divide and conquer. Fork breaks down tasks and joins to collect data.

Work stealing mode

Compared with the general implementation of thread pool, the advantage of fork/join framework is reflected in the processing method of the tasks contained in it. In the general thread pool, if the task being executed by a thread cannot continue to run for some reason, the thread will be in the waiting state. In the implementation of fork/join framework, If a subproblem cannot continue to run because it waits for the completion of another subproblem, the thread handling the subproblem will actively look for other subproblems that have not yet run to execute. This method reduces the waiting time of the thread and improves the performance

Keywords: Java stream java8

Added by msmith29063 on Thu, 23 Sep 2021 09:20:57 +0300