13JavaSE函数式编程&Stream流

13.1常用的函数式接口总结

接口名称 方法名称 抽象/默认 延迟/终结 方法描述
Supplier get 抽象 终结 供给型接口,无参有返回值,主要用于
Consumer accept 抽象 终结 消费型接口,有参数无返回值
andThen 默认 延迟
Function apply 抽象 终结 函数型接口,有参数有返回值
andThen 默认 延迟
compose 默认 延迟
Predicate test 抽象 终结 断言型接口,元芳你怎么看
and 默认 延迟
or 默认 延迟
negate 默认 延迟

notes:

  • 延迟方法:只是在拼接Lambda函数模型的方法,并不立即执行得到结果。
  • 终结方法:根据拼好的Lambda函数模型,立即执行得到结果值的方法。

13.2 Stream流

13.2.1 获取流的三种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[] args) {

// Collection 集合
Collection c = new ArrayList<String>();
Stream stream1 = c.stream();
System.out.println("stream1 = " + stream1);

// List 集合
ArrayList<String> list = new ArrayList<>();
Stream<String> stream2 = list.stream();
System.out.println("stream2 = " + stream2);

// Set 集合
HashSet<String> set = new HashSet<>();
Stream<String> stream3 = set.stream();
System.out.println("stream3 = " + stream3);
}

Map集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[] args) {

// Map 集合
HashMap<String, Integer> map = new HashMap<>();

// 获取流
// 1. keySet
Stream<String> stream1 = map.keySet().stream();
// 2. values
Stream<Integer> stream2 = map.values().stream();
// 3. entrySet
Stream<Map.Entry<String, Integer>> stream3 = map.entrySet().stream();

System.out.println("stream1 = " + stream1);
System.out.println("stream2 = " + stream2);
System.out.println("stream3 = " + stream3);
}

13.2.2 流的常用方法

** 终结方法**:返回值类型不再是Stream接口自身类型的方法,因此不再支持类似StringBuilder那样的链式调用。本小节中,终结方法包括count和forEach方法。
  • 非终结方法:返回值类型仍然是Stream接口自身类型的方法,因此支持链式调用。(除了终结方法外,其余方法均为非终结方法。)
 终结方法:逐一处理:forEach,统计个数:count

 非终结方法:过滤:filter,取用前几个:limit,跳过前几个:skip,映射:map

组合: 使用Stream接口的静态方法concat
方法名 方法作用 方法种类 是否支持链式调用
count 统计个数 终结
forEach 逐一处理 终结
filter 过滤 函数拼接
limit 取用前几个 函数拼接
skip 跳过前几个 函数拼接
map 映射 函数拼接
concat 组合 函数拼接

并发流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
转换为并发流
1. Stream的父接口java.util.stream.BaseStream中定义了一个parallel方法:
2.在通过集合获取流时,也可以直接调用parallelStream方法来直接获取支持并发操作的流
default Stream<E> parallelStream() {...
收集集合三种:
收集到集合中
Stream流提供collect方法,其参数需要一个java.util.stream.Collector<T,A, R>接口对象来指定收集到哪种集合中。幸运的是,java.util.stream.Collectors类提供一些方法,可以作为Collector接口的实例:

- public static <T> Collector<T, ?, List<T>> toList():转换为List集合。
- public static <T> Collector<T, ?, Set<T>> toSet():转换为Set集合。
收集到数组中
Stream提供toArray方法来将结果放到一个数组中,由于泛型擦除的原因,返回值类型是Object[]的:

扩展:解决泛型数组问题

有了Lambda和方法引用之后,可以使用toArray方法的另一种重载形式传递一个IntFunction<A[]>的函数,继而从外面指定泛型参数。方法签名:

<A> A[] toArray(IntFunction<A[]> generator);

有了它,上例代码中不再局限于Object[]结果,而可以得到String[]结果

Powered by Hexo and Hexo-theme-hiker

Copyright © 2016 - 2018 Francis的个人博客 All Rights Reserved.

UV : | PV :