函数式编程

函数式编程关心数据的映射,命令式编程关心解决问题的步骤

函数式编程是种编程方式,它将电脑运算视为函数的计算。函数编程语言最重要的基础是λ演算(lambda calculus),而且λ演算的函数可以接受函数当作输入(参数)和输出(返回值)。

Lambda表达式

Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。Lambda表达式可以表示闭包(注意和数学传统意义上的不同)。

核心原则:可推导可省略

基本格式:

1
(参数列表)->(代码)

实例一:

1
2
3
4
5
6
7
8
9
10
>public class LambdaDemo01 {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("新线程中run方法被执行了");
}
}).start();
}
}

Lambda表达式:

1
2
3
4
5
>public class LambdaDemo01 {
public static void main(String[] args) {
new Thread(() -> System.out.println("新线程中run方法被执行了")).start();
}
}

实例二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>import java.util.function.IntBinaryOperator;
public class LambdaDemo01 {
public static void main(String[] args) {
int i = calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
System.out.println(i);

public static int calculateNum(IntBinaryOperator operator) {
int a = 10;
int b = 20;
return operator.applyAsInt(a, b);
}
}

Lambda表达式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>import java.util.function.IntBinaryOperator;
public class LambdaDemo01 {
public static void main(String[] args) {
int i = calculateNum((int left, int right) -> {
return left + right;
});
System.out.println(i);
}

public static int calculateNum(IntBinaryOperator operator) {
int a = 10;
int b = 20;
return operator.applyAsInt(a, b);
}
}

实例三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>import java.util.function.IntPredicate;
public class LambdaDemo01 {
public static void main(String[] args) {
printNum(new IntPredicate() {
@Override
public boolean test(int value) {
return value % 2 == 0;
}
});
}
public static void printNum(IntPredicate predicate) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i : arr) {
if (predicate.test(i)) {
System.out.println(i);
}
}
}
}

Lambda表达式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>import java.util.function.IntPredicate;
public class LambdaDemo01 {
public static void main(String[] args) {
printNum((int value) -> {
return value % 2 == 0;
});
}
public static void printNum(IntPredicate predicate) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i : arr) {
if (predicate.test(i)) {
System.out.println(i);
}
}
}
}

实例四:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>import java.util.function.Function;
import java.util.function.IntPredicate;
public class LambdaDemo01 {
public static void main(String[] args) {
Integer integer = typeConver(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.valueOf(s);
}
});
System.out.println(integer);
}
public static <R> R typeConver(Function<String,R> function){
String str = "1235";
R result = function.apply(str);
return result;
}
}

Lambda表达式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>import java.util.function.Function;
import java.util.function.IntPredicate;
public class LambdaDemo01 {
public static void main(String[] args) {
Integer integer = typeConver((String s) -> {
return Integer.valueOf(s);
});
System.out.println(integer);
}
public static <R> R typeConver(Function<String,R> function){
String str = "1235";
R result = function.apply(str);
return result;
}
}

实例五:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;

public class LambdaDemo01 {
public static void main(String[] args) {
foreachArr(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
}

public static void foreachArr(IntConsumer consumer) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i :
arr) {
consumer.accept(i);
}
}
}

Lambda表达式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;

public class LambdaDemo01 {
public static void main(String[] args) {
foreachArr(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
}

public static void foreachArr(IntConsumer consumer) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i :
arr) {
consumer.accept(i);
}
}
}

省略规则:

  1. 参数类型可以省略
  2. 方法体只有一句代码时打括号return和唯一一句代码的分号可以省略
  3. 方法体只有一个参数时小括号可以省略

Stream流

  1. stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果;
  2. stream不会改变数据源,通常情况下会产生一个新的集合;
  3. stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。
  4. 对stream操作分为终端操作和中间操作,那么这两者分别代表什么呢?
    1. 终端操作:会消费流,这种操作会产生一个结果的,如果一个流被消费过了,那它就不能被重用的。
    2. 中间操作:中间操作会产生另一个流。因此中间操作可以用来创建执行一系列动作的管道。一个特别需要注意的点是:中间操作不是立即发生的。相反,当在中间操作创建的新流上执行完终端操作后,中间操作指定的操作才会发生。所以中间操作是延迟发生的,中间操作的延迟行为主要是让流API能够更加高效地执行。
  5. stream不可复用,对一个已经进行过终端操作的流再次调用,会抛出异常。

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
//id
private Long id;
//书名
private String name;
//分类
private String category;
//评分
private Integer score;
//简介
private String intro;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Objects;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author implements Comparable<Author>{
//id
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books;
@Override
public int compareTo(Author o) {
return o.getAge()-this.getAge();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamDemo {
public static void main(String[] args) {
List<Author> authors = getAuthors();
test01(authors);
}

private static void test01(List<Author> authors) {
//把集合转换成流
authors.stream()
.distinct()
.filter(author -> {
System.out.println("test");
return author.getAge() < 18;
})
.forEach(author -> System.out.println(author.getName()));
}
private static List<Author> getAuthors() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
Author author2 = new Author(2L,"亚拉索",15,"狂风也追逐不上他的思考速度",null);
Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
Author author4 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);

//书籍列表
List<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();

books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));

books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));

books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);

List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
return authorList;
}
}
  1. Sequence of elements(元素序列):简单来说,就是我们操作的集合中的所有元素
  2. source(数据源) :Stream流的作用就是操作数据,那么source 就是为Stream提供可操作的源数据(一般,集合、数组或I/OI/O resources 都可以成为Stream的source )
  3. Data processing operations(数据处理操作):上面菜单程序代码中出现的filter、sorted、map、collect,以及reduce、find、match等都属于Stream 的一些操作数据的方法接口。这些操作可以顺序进行,也可以并行执行。
  4. Pipelining(管道、流水线):Stream对数据的操作类似数据库查询,也像电子厂的生产流线一样,Stream的每一个中间操作(后面解释什么是中间操作)比如上面的filter、sorted、map,每一步都会返回一个新的流,这些操作全部连起来就是想是一个工厂得生产流水线 :
    img
  5. Internal iteration(内部迭代):Stream API 实现了对数据迭代的封装,不用你再像操作集合一样,手动写for循环显示迭代数据。

Stream最主要的三组成部分

  1. 创建流,也就是Stream开始的地方,负责创建一个Stream实例
  2. 中间操作,主要是一些对数据的过滤筛选,添加删除等等操作,形成一个流程链。
  3. 收尾,也就是终端操作,我感觉更适合叫终结操作,终端操作会从流的流水线(中间操作)生成结果

Stream流的生命周期:同一个流只能遍历一次,遍历完后,这个流就已经被消费掉了。你如果还需要在遍历,可以从原始数据源那里再获得一个新的流来重新遍历一遍。

Stream操作分类

常用中间操作

操作 类型 返回类型 操作参数 函数描述符
filter 中间 Stream Predicate T->boolean
map 中间 Stream Function<T,R> T->R
limit 中间 Stream
sorted 中间 Stream Comparator (T,T)->int
distinct 中间 Stream

常用终端操作

操作 类型 目的
forEach 终端 消费流中的每个元素并对其应用Lambda,返回void
count 终端 返回流中元素的个数(long)
collect 终端 把流归约成一个集合,如List、Map、Integer

流的常用创建方法

  1. 使用Collection下的 stream() 和 parallelStream() 方法

    1
    2
    3
    List<String> list = new ArrayList<>();
    Stream<String> stream = list.stream(); //获取一个顺序流
    Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
  2. 使用Arrays 中的 stream() 方法,将数组转成流

    1
    2
    Integer[] nums = new Integer[10];
    Stream<Integer> stream = Arrays.stream(nums);
  3. 使用Stream中的静态方法:of()、iterate()、generate()

    1
    2
    3
    4
    5
    6
    7
    Stream<Integer> stream = Stream.of(1,2,3,4,5,6);

    Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6);
    stream2.forEach(System.out::println); // 0 2 4 6 8 10

    Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
    stream3.forEach(System.out::println);
  4. 使用 BufferedReader.lines() 方法,将每行内容转成流

    1
    2
    3
    BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt"));
    Stream<String> lineStream = reader.lines();
    lineStream.forEach(System.out::println);
  5. 使用 Pattern.splitAsStream() 方法,将字符串分隔成流

    1
    2
    3
    Pattern pattern = Pattern.compile(",");
    Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
    stringStream.forEach(System.out::println);

流的中间操作

  1. 过滤通过 filter() 方法可以从流中筛选出我们想要的元素

    distinct() 方法是一个中间操作(去重),它会返回一个新的流(没有共同元素)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    private static void test01(List<Author> authors) {
    authors.stream()//把集合转换成流
    .distinct()
    .filter(author -> {
    System.out.println("test");
    return author.getAge() < 18;
    })
    .forEach(author -> System.out.println(author.getName()));
    }

    filter() 方法接收的是一个 Predicate(Java 8 新增的一个函数式接口,接受一个输入参数返回一个布尔值结果)类型的参数,因此,我们可以直接将一个 Lambda 表达式传递给该方法。

  1. 如果想通过某种操作把一个流中的元素转化成新的流中的元素,可以使用 map() 方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    private static void test05() {
    // 打印所有作家的姓名
    List<Author> authors = getAuthors();

    authors.stream()
    .map(new Function<Author, String>() {
    @Override
    public String apply(Author author) {
    return author.getName();
    }
    })
    .forEach(s -> System.out.println(s));
    }

    map() 方法接收的是一个 Function(Java 8 新增的一个函数式接口,接受一个输入参数 T,返回一个结果 R)类型的参数,此时参数 为 String 类的 length 方法,也就是把 Stream 的流转成一个 Stream 的流。

  1. sorted() 方法按自然顺序排序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    private static void test07() {
    List<Author> authors = getAuthors();
    //对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
    authors.stream()
    .distinct()
    .sorted(new Comparator<Author>() {
    @Override
    public int compare(Author o1, Author o2) {
    return o2.getAge() - o1.getAge();
    }
    })
    .forEach(author -> System.out.println(author.getAge()));
    }

    返回由该流的元素组成的流,按自然顺序排序。如果此流的元素不是 Comparable,则在执行终端操作时可能会抛出 java.lang.ClassCastException。对于有序流,排序是稳定的。对于无序流,不保证稳定性。

    (如果调用空参的 sorted() 方法,需要流中的元素是实现了 Comparable 接口)

https://zhuanlan.zhihu.com/p/339038230

https://baijiahao.baidu.com/s?id=1662741032559775199&wfr=spider&for=pc

https://www.cnblogs.com/MrYuChen-Blog/p/14042801.html

https://blog.csdn.net/y_k_y/article/details/84633001?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_antiscanv2&utm_relevant_index=1

查看评论