java8 : 流

 1 package day02.com.offcn.test;
 2 
 3 import java.io.IOException;
 4 import java.nio.charset.Charset;
 5 import java.nio.file.Files;
 6 import java.nio.file.Paths;
 7 import java.util.*;
 8 import java.util.stream.*;
 9 
10 /**
11  * @author: CC
12  * @date: 2019/9/8
13  */
14 public class 流 {
15     //流的创建
16     public static void main(String[] args) throws IOException {
17         //由值创建流,静态方法Stream.of
18         Stream<String> stream = Stream.of("JAVA 8","Lambdas","In","Action");
19 
20         //由数组创建流, 静态方法Arrays.stream
21         int[] numbers = {3,4,5,6,11,13};
22         int sum = Arrays.stream(numbers).sum();
23 
24         //由文件生成流
25         Stream<String> lines = Files.lines(Paths.get("D:/aa.txt"), Charset.defaultCharset());
26         long sum1 = lines.count();
27 
28         //由函数生成流,生成无限流
29         //迭代
30         Stream.iterate(0,n->n+2)
31                 .limit(10)
32                 .forEach(System.out::println);
33         //生成
34         Stream.generate(Math::random)
35                 .map(aDouble -> aDouble*100)
36                 .limit(10)
37                 .forEach(System.out::print);
38 
39         //collection构建流,集合流
40         Collection collection = new HashSet();
41         collection.stream();
42 
43 //        中间操作(intermediate)主要有以下方法(此类型的方法返回的都是Stream对象):
44 //        map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、
45 //        limit、 skip、 parallel、 sequential、 unordered
46 
47         List<String> list = Arrays.asList("aaa","ddd","bbb","ccc","a2a","d2d","b2b","c2c","a3a","d3d","b3b","c3c");
48 
49         List list1 = list.stream()
50                 .filter(s -> s.equals("aaa"))
51                 .map(s -> "df")
52                 .distinct()
53                 .limit(10)
54                 .skip(5)
55                 .mapToInt(value -> 10)
56                 .mapToDouble(value -> 0.1)
57                 .mapToLong(value -> 23)
58                 .mapToObj(value -> "dsfs")
59                 .sorted()
60                 .parallel()
61                 .peek(System.out::print)
62                 .collect(Collectors.toList());
63         //留意装箱。自动装箱和拆箱操作会大大降低性能。Java 8中有原始类型流(IntStream、
64         //LongStream、DoubleStream)来避免这种操作,但凡有可能都应该用这些流。
65         
66         Object[] obj = list1.stream().toArray();
67         Arrays.asList(obj).stream().max((o1, o2) -> 0);
68         Arrays.asList(obj).stream().min((o1, o2) -> 0);
69         boolean boo = Arrays.asList(obj).stream().allMatch(o -> true);
70         Arrays.asList(obj).stream().forEach(System.out::print);
71         Arrays.asList(obj).stream().count();
72         Arrays.asList(obj).stream().iterator();
73 //        终端操作(terminal)主要有以下方法:
74 //        forEach、 forEachOrdered、 toArray、 reduce、 collect、
75 //        min、 max、 count、 anyMatch、 allMatch、 noneMatch、
76 //        findFirst、 findAny、 iterator
77     }
78 }

猜你喜欢

转载自www.cnblogs.com/lovemeng1314/p/11503479.html