current position:Home>Analysis of stream stream in Java

Analysis of stream stream in Java

2022-06-24 09:11:38ldcaws

Stream Flow is Java8 An important new feature provided in , It allows developers to process collections declaratively . among parallelStream In fact, it is a flow of parallel execution , It passes the default ForkJoinPool, May increase the speed of your multithreaded tasks .
Stream Flow characteristics are as follows

  • stream Don't store data , Instead, the data is calculated according to specific rules , Generally, the result will be output ;
  • stream It doesn't change the data source , Usually a new set will be generated ;
  • stream It has the characteristics of delayed execution , Only when the terminal operation is called , The intermediate operation will be performed ;
  • stream Do not reuse , Calling a stream that has performed terminal operations again will throw an exception ;

Stream There are many operation methods for collection defined in the stream interface , There are two main categories : Intermediate operation and terminal operation .
 Insert picture description here

  • Intermediate operation : Back to a stream , In this way, multiple intermediate operations can be connected , Form a call chain , So it can be converted to another stream . Unless a post chain operation exists , Otherwise, the intermediate operation will not process any results .
  • Terminal operation : Returns a specific result , Such as list etc. .

Common intermediate operation methods are :limit、skip、distinct、sorted etc. .
Common terminal operation methods include :forEach、count、toArray、reduce etc. .
Common collection operation methods include :collect.
Use Stream After the flow mode operation is completed , Through the collection method collect Collect data into collections , Tool class Collectors Specific collection methods are provided , as follows

  • toList: Collect elements into List Collection ;
  • toSet: Collect elements into Set Collection ;
  • toMap: Collect elements into Map Collection ;

Stream performance

  • In a scenario with a small amount of data (size<1000)
    stream The flow of foreach Processing efficiency is not as good as iterator The efficiency of iteration , But in fact, these processing tasks themselves actually run in less than milliseconds , This efficiency gap has little impact on the general business , and stream Flow can make the code simpler and more elegant ;
  • In a multi data scenario (size>10000)
    stream The flow of foreach Treatment efficiency higher than iterator The efficiency of iteration , In particular, parallel streams are used , stay cpu Just when threads are allocated to multiple cores , It's very efficient .
  • parallelStream Parallel flow
    parallelStream suffer cpu The environmental impact is great , When not assigned to multiple cpu Core time , Plus the introduction of forkJoinPool The cost of , The operation efficiency is not as good as stream flow .

Here are the answers for loop 、foreach loop 、stream.foreach loop 、parallelStream.foreach Test the performance of the loop

public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        Long startTime = System.currentTimeMillis();
        forMethod(list);
        Long endTime = System.currentTimeMillis();
        System.out.println("result:" + (endTime - startTime));//29 15 31 15 16
    }

    private static void forMethod(List<Integer> list) {
        for (Integer i : list) {
            System.out.println("------" + i);
        }
    }
public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        Long startTime = System.currentTimeMillis();
        foreachMethod(list);
        Long endTime = System.currentTimeMillis();
        System.out.println("result:" + (endTime - startTime));//85 80 84 84 85
    }

    private static void foreachMethod(List<Integer> list) {
        list.forEach(integer -> {
            System.out.println("------" + integer);
        });
    }
public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        Long startTime = System.currentTimeMillis();
        streamMethod(list);
        Long endTime = System.currentTimeMillis();
        System.out.println("result:" + (endTime - startTime));//116 115 85 84 84
    }

    private static void streamMethod(List<Integer> list) {
        list.stream().forEach(integer -> {
            System.out.println("------" + integer);
        });
    }
public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        Long startTime = System.currentTimeMillis();
        parallelStreamMethod(list);
        Long endTime = System.currentTimeMillis();
        System.out.println("result:" + (endTime - startTime)); //179 138 140 122 175
    }

    private static void parallelStreamMethod(List<Integer> list) {
        list.parallelStream().forEach(integer -> {
            System.out.println("------" + integer);
        });
    }

The amount of data is 1000 when , The order of efficiency is for>foreach>stream.foreach>parallelStream.foreach.
Theoretically , More data ,stream The more efficient ,parallelStream Will be the most efficient and parallel processing . But the selection needs to think about the scene , Avoid data security issues .

copyright notice
author[ldcaws],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240744019287.html

Random recommended