Stream Trilogy - create stream
Flow can be divided into two types: finite flow and infinite flow. Finite flow refers to the finite number of elements in the flow and infinite flow refers to the infinite number of elements in the flow. No matter finite flow or infinite flow, there will be no intermediate operation before terminal operation.
1. Finite flow creation
1.1 creating a flow from a collection
The stream () API of list/set can be used to create stream
// Create finite stream 1: get stream through set (list,set), Map cannot get stream @Test public void createByListSet(){ // Creating parallel streams using list List<String> list = new ArrayList<>(); Stream<String> listParallelStream = list.parallelStream(); // Using set to create a serial stream Set<String> set = new HashSet<>(); Stream<String> setStream = set.stream(); }
1.2 create by array
Arrays can be constructed by Arrays.stream(), which has many overloaded methods
// Create finite stream 2: create stream from array @Test public void createByArray(){ String[] array = new String[3]; Stream<String> arrayStream = Arrays.stream(array); long[] longArray = new long[3]; LongStream longStream = Arrays.stream(longArray); int[] intArray = new int[3]; IntStream intStream = Arrays.stream(intArray); double[] doubleArray = new double[3]; DoubleStream doubleStream = Arrays.stream(doubleArray); }
1.3 create through Stream.of
Stream.of can only receive arrays as parameters, and the receiving set will treat the whole set as an element in the stream
// Create finite stream 3: create stream by Stream.of method, with array as parameter @Test public void createByConstants(){ Stream<String> stream = Stream.of("java", "Linux", "mysql", "nginx"); Stream<String> stream2 = Stream.of(new String[]{"a", "b", "c", "d"}); stream.forEach(System.out::println); stream2.forEach(System.out::println); }
1.4 get stream through file
// Create finite stream 4: get stream from file @Test public void createByFile() throws Exception{ Stream<String> fileStream = Files.lines(Paths.get("pom.xml")); fileStream.forEach(System.out::println); }
2. Infinite flow creation
2.1 generative creation
// Create infinite stream 1: generate 5 random numbers @Test public void test_generate(){ Stream<Double> stream = Stream.generate(Math::random).limit(5); stream.forEach(System.out::println); }
2.2 iterative creation
Iterative creation is similar to recursion
// Create infinite flow 2: iterative creation,(Infinite flow usually needs cooperation limit Use,Otherwise it will be created indefinitely) @Test public void test_iterate(){ Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5); stream.forEach(System.out::println); } //Test Fibonacci series @Test public void test_febinache(){ Stream<Integer> stream = Stream .iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(8) .map(t -> t[0]); stream.forEach(System.out::println); }