Java 8 函数式编程

 1 Java 8 函数式编程
 2 java.util.function.*
 3 @FunctionalInterface
 4 都是函数接口,没有成员(状态)
 5 
 6 高阶函数:参数或返回值为函数
 7 
 8 方法引用:类名::方法名
 9 可以 类名::new、String[]::new
10 
11 流操作
12 Stream.of("-1", "0", "1") // 生成
13 .map(函数) // 映射
14 .filter(返回布尔值函数) // 过滤器(重构:找for中if)
15 .flatMap(函数) // 平面映射:多个流合并
16 .min(Comparator.comparing(x -> x.getLength()))
17 .reduce(0, (a, b) -> a+b); // 缩小
18 a一开始是第一个参数0,b是不断传入的流元素,
19 这个式子的功能是求和,
20 可以用Integer的sum函数替代第二个式子,
21 写成.reduce(0, Integer::sum);
22 .forEach // 遍历,可以不纯
23 .peek(e -> System.out.println("Mapped value: " + e))
24 可以记录中间值用于调试,不会像forEach那样使得流不可用
25 .collect(Collector)
26 interface Collector<T, A, R> // 输入类型,累加器,返回类型
27 接口方法:
28 Supplier<A> supplier(); // 供应器:创建容器
29 BiConsumer<A, T> accumulator(); // 累加器:类似reduce的第二参数(函数式)
30 BinaryOperator<A> combiner(); // 组合器:合并容器
31 Function<A, R> finisher(); // 完工者:转换为想要的结果类型
32 Set<Characteristics> characteristics(); // 特征:返回不可变集合
33 .collect(Collectors.toList()); // 采集:生成列表
34 .collect(Collectors.toCollection(TreeSet::new))
35 .collect(Collectors.joining(", ", "[", "]"));
36 .collect(Collectors.summingInt(Integer::valueOf))
37 .collect(Collectors.partitioningBy(x->x.length()>1)); // Map<Boolean, List<T>>
38 .collect(Collectors.groupingBy(String::length)) // Map<R, List<T>>
39 .collect(Collectors.groupingBy(String::length,Collectors.counting()))
40 下游收集器 = Collectors.mapping(String::length, Collectors.toList());
41 .collect(Collectors.groupingBy(String::length,下游收集器));
42 .collect(Collectors.maxBy(Comparator 比较规则))
43 
44 .parallel() // BaseStream 并行流
45 集合.parallelStream()
46 影响性能因素:1.数据大小、2.结构、3.装箱、4.核心数、5单元处理开销
47 分解性能:
48 好:ArrayList、数组、IntStream.range
49 中:HashSet、TreeSet
50 差:LinkedList、Streams.iterate、BefferedReader.lines
51 无状态:filter、flatMap(速度快)
52 有状态:sorted、distinct、limit
53 
54 .mapToInt() // 映射并转换为基本类型,其他类似
55 基本类型速度快、占用小
56 
57 IntStream.of(1, 2, 3).summaryStatistics()
58 .getCount()
59 .getSum()
60 .getMin()
61 .getAverage()
62 .getMax()
63 
64 // 供应者:只有get方法的函数
65 public interface Supplier<T> { T get(); }
66 
67 // 判定:返回布尔值的函数
68 Predicate<T> { boolean test(T t); and; 否定 negate; or; isEqual }
69 
70 // 函数
71 Function<T, R> {R apply(T t); 组合compose; andThen; 同一 identity}
72 
73 重载时 javac 会选最具体的
74 
75 Optional.of("a")
76 .isPresent()
77 .get()
78 .orElse("b")
79 .orElseGet(只有get方法的函数)
80 
81 TDD 测试驱动开发
82 BDD 行为驱动开发,TDD 的一个变种
83 DSL 领域专用语言
84 
85 public class 类名 {{ }} // 匿名构造函数
86 public class 类名 { public 类名() {} }
87 
88

 

 1 并行运行基于集合流的质数计数程序
 2 public long countPrimes(int upTo) {
 3     return IntStream.range(1, upTo)
 4             .parallel()
 5             .filter(this::isPrime)
 6             .count();
 7 }
 8 private boolean isPrime(int number) {
 9     return IntStream.range(2, number)
10             .allMatch(x -> (number % x) != 0);
11 }
12 
13 使用 Map 的 computeIfAbsent 方法高效计算斐波那契数列。
14 这里的“高效”是指避免将那些较小的序列重复计算多次。
15 public class Fibonacci {
16 
17     private final Map<Integer,Long> cache;
18 
19     public Fibonacci() {
20         cache = new HashMap<>();
21         cache.put(0, 0L);
22         cache.put(1, 1L);
23     }
24 
25     public long fibonacci(int x) {
26         return cache.computeIfAbsent(x, n -> fibonacci(n-1) + fibonacci(n-2));
27     }
28 
29 }
30 
31 Map.merge(key,value,BiFunction)
32 
33 BufferedReader::lines

 

posted @ 2023-03-30 15:53  何童鞋  阅读(116)  评论(0编辑  收藏  举报