Java 8 in Stream (stream) conversion

Stream flow is an important concept introduced in Java 8, the introduction of truly functional programming style to Java. If the master can be subject to various business scenarios under stream conversion, can be easily prepared by using functional style business logic.
Stream generating method for various scenarios:
1 can be easily converted to a set of elements by Stream.of () to become stream, the parameter may be a comma-separated set of objects, or may be a collection of objects, or an array.
1 Stream stream1 = Stream.of("It's ", "a ", "wonderful ", "day ", "for ", "pie!");
2 Stream stream2 = Stream.of(3.14159, 2.718, 1.618);
3 Stream stream3 = Stream.of(new ArrayList());
4 Integer[] integers = {1,2,3};
5 Stream stream4 = Stream.of(integers);

 

2. Each set may be generated by calling a flow stream () method.
1 List<Long> longList = new ArrayList();
2 Stream stream = longList.stream();

 

3. Rondom class object can generate a random number streams
1 Random rand = new Random(47);
2 Stream stream = rand.ints().boxed();

 

4. IntStream class provides range () method for generating a stream of integer sequences. When writing cycle, this method is more convenient:
 1 // import static java.util.stream.IntStream.*;
 2 // 传统方法:
 3 int result = 0;
 4 for (int i = 10; i < 20; i++){
 5     result += i;
 6 }
 7 System.out.println(result);
 8 // for-in 循环:
 9 result = 0;
10 for (int i : range(10, 20).toArray()){
11     result += i;
12 }

 

5. Builder design mode (also known as the constructor mode), first create a builder object passed to its constructor more information, final implementation "structure." Stream library provides such Builder, you can produce a stream by the object builder.
 1 // streams/FileToWordsBuilder.java
 2 import java.io.*;
 3 import java.nio.file.*;
 4 import java.util.stream.*;
 5  
 6 public class FileToWordsBuilder {
 7     Stream.Builder<String> builder = Stream.builder();
 8  
 9     public FileToWordsBuilder(String filePath) throws Exception {
10         Files.lines(Paths.get(filePath))
11              .skip(1) // 略过开头的注释行
12              .forEach(line -> {
13                   for (String w : line.split("[ .?,]+"))
14                       builder.add(w);
15               });
16     }
17  
18     Stream<String> stream() {
19         return builder.build();
20     }
21  
22     public static void main(String[] args) throws Exception {
23         new FileToWordsBuilder("Cheese.dat")
24             .stream()
25             .limit(7)
26             .map(w -> w + " ")
27             .forEach(System.out::print);
28     }
29 }

 

 

Guess you like

Origin www.cnblogs.com/tianxiafeiyu/p/12216775.html