Creating Stream

1. Create Stream        

create Stream from Collections;

create Stream from values;

create Stream from Arrays;

craeate Stream from files;

craeate Stream from functions

Code Example:

 1 package com.cy.java8;
 2 
 3 import java.io.IOException;
 4 import java.nio.file.Files;
 5 import java.nio.file.Path;
 6 import java.nio.file.Paths;
 7 import java.util.Arrays;
 8 import java.util.List;
 9 import java.util.stream.Stream;
10 
11 public class CreateStream {
12 
13     public static void main(String[] args) {
14         createStreamFromCollection () forEach (the System.out :: the println);.
 15  
16          createStreamFromValues () forEach (the System.out :: the println);.
 . 17  
18 is          . createStreamFromArrays () forEach (the System.out :: the println);
 . 19  
20 is          createStreamFromFile ( ) .forEach (the System.out :: the println);
 21 is      }
 22 is  
23 is  
24      / ** 
25       * Collection Create from Stream
 26 is       the sequence of elements * list here does not change into strem, what order the original, stream in what is.
27       * @return 
28       * / 
29      Private  static Stream <String> createStreamFromCollection () {
30         List<String> list = Arrays.asList("hello", "world", "stream");
31         return list.stream();
32     }
33 
34     private static Stream<String> createStreamFromValues(){
35         return Stream.of("hello", "world", "stream");
36     }
37 
38     private static Stream<String> createStreamFromArrays(){
39         String[] strings = new String[]{"hello", "world", "stream"};
40         return Arrays.stream(strings);
41     }
42 
43     /**
44      * create stream from file
45      * @return
46      */
47     private static Stream<String> createStreamFromFile(){
48         Path path = Paths.get("F:\\IdeaProjects\\Java8Learning\\java8\\src\\main\\java\\com\\cy\\java8\\CreateStream.java");
49         Stream<String> lines = null;
50         try {
51             lines = Files.lines(path);
52         } catch (IOException e) {
53             throw new RuntimeException(e);
54         }
55         return lines;
56     }
57 }

Print results are as follows:

the Hello 
world 
Stream 
the Hello 
world 
Stream 
the Hello 
world 
Stream 
Package Penalty for com.cy.java8; 

Import java.io.IOException; 
.... 
the CreateStream.java file branches print out ...

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-----

Guess you like

Origin www.cnblogs.com/tenWood/p/11503464.html