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 = list.stream();
2. The static method stream() of array gets the array stream
Employee[] emps = new Employee[10];
Stream<Employee> stream = Arrays.stream(emps);
3. Static method of stream class ()
Stream<String> stream = Stream.of("aa","bb","cc","dd");
4. Create an infinite stream
iteration
Stream<Integer> stream = Stream.iterate(0,x->x+2);
stream.limit(10).forEach(System.out::println);
generate
Stream.generate(()->Math.random())
	  .limit(5)
	  .forEach(System.out::println);

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

mapping

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  = lists.stream().flatMap(l -> l.stream())
        											 .collect(Collectors.toList());
sort

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

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 = emps.stream().map(Employee::getAge).collect(Collectors.toList());
        Set<Integer> collect1 = emps.stream().map(Employee::getAge).collect(Collectors.toSet());
        Map<Integer, Double> collect2 = emps.stream().collect(Collectors.toMap(Employee::getAge, Employee::getSalary));
        // Specifies the collection type
        HashSet<Integer> collect3 = emps.stream().map(Employee::getAge).collect(Collectors.toCollection(HashSet::new));
         // Multilevel grouping
        Map<Double, Map<String, List<Employee>>> collect5 = emps.stream().collect(Collectors.groupingBy(Employee::getSalary, Collectors.groupingBy(e -> {
            if (e.getAge() < 20) {
                return "juvenile";
            } else if (e.getAge() < 50) {
                return "middle age";
            } else {
                return "old age";
            }
        })));
         //partition
        Map<Boolean, List<Employee>> collect7 = emps.stream().collect(Collectors.partitioningBy(e -> e.getAge() > 20));
        //calculation
        DoubleSummaryStatistics collect8 = emps.stream().collect(Collectors.summarizingDouble(Employee::getAge));

// joining
        String collect9 = emps.stream().map(Employee::getName).collect(Collectors.joining(","));
        System.out.println(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