面向对象编程是对数据进行抽象;函数式编程是对行为进行抽象。
Lambda 特点
面向对象编程是对数据进行抽象;函数式编程是对行为进行抽象。 核心思想: 使用不可变值和函数,函数对一个值进行处理,映射成另一个值。
- 内部可以使用静态、非静态和局部变量
- 在Java中又称为闭包或匿名函数
- 有个限制,那就是只能引用 final 或 final 局部变量
Lambda 使用以及 Stream 下的接口
stream & parallelStream
parallelStream其实就是一个并行执行的流,它通过默认的ForkJoinPool,可能提高你的多线程任务的速度。
stream中常用方法
- stream(), parallelStream()
- filter()
- findFirst()
- sorted()
- forEach()
- map(), reduce()
- flatMap()
- collect(Collectors.toList())
- distinct(),limit()
- count()
- min(), max()
示例
findFirst()
List<User> userList = Arrays.asList(new User("zhangsan","张三","123456","男","123@qq.com","")
,new User("zhangsan1","张三","123456","女","123@qq.com",""));
Optional<User> first = userList.stream().filter(user ->
StringUtils.endsWithIgnoreCase("张三", user.getUserName())).findFirst();
System.out.println(first);
输出:
Optional[User[id=null, loginName='zhangsan', userName='张三', password='123456', sex='男', email='123@qq.com', address='']]
sorted()
按照年龄排序
List<User> userList = Arrays.asList(new User("zhangsan", "张三", "123456", "男", "123@qq.com", "", 23)
, new User("zhangsan1", "张三", "123456", "女", "123@qq.com", "", 19));
List<User> collect = userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
System.out.println(collect);
输出:
[User[id=null, loginName='zhangsan1', userName='张三', password='123456', sex='女', email='123@qq.com', address='', age=19], User[id=null, loginName='zhangsan', userName='张三', password='123456', sex='男', email='123@qq.com', address='', age=23]]
distinct()
List<User> userList = Arrays.asList(new User("zhangsan", "张三", "123456", "男", "123@qq.com", "", 23)
, new User("zhangsan1", "张三", "123456", "女", "123@qq.com", "", 19));
List<String> collect = userList.stream().map(User::getLoginName).distinct().collect(Collectors.toList());
System.out.println(collect);
输出:
[zhangsan, zhangsan1]
count()
List<User> userList = Arrays.asList(new User("zhangsan", "张三", "123456", "男", "123@qq.com", "", 23)
, new User("zhangsan1", "张三", "123456", "女", "123@qq.com", "", 19));
long count = userList.stream().filter(user -> user.getAge() > 19).count();
System.out.println(count);
输出:
1
macth
anyMatch
List<User> userList = Arrays.asList(new User("zhangsan", "张三", "123456", "男", "123@qq.com", "", 23)
, new User("zhangsan1", "张三", "123456", "女", "123@qq.com", "", 19));
boolean b = userList.stream().anyMatch(user -> user.getAge() == 19);
System.out.println(b);
输出:
true
allmatch
List<User> userList = Arrays.asList(new User("zhangsan", "张三", "123456", "男", "123@qq.com", "", 23)
, new User("zhangsan1", "张三", "123456", "女", "123@qq.com", "", 19));
boolean b = userList.stream().allMatch(user -> user.getAge() == 19);
System.out.println(b);
输出:
false
四大内置函数接口
消费型接口
Consumer< T> void accept(T t)有参数,无返回值的抽象方法;
供给型接口
Supplier < T> T get() 无参有返回值的抽象方法;
断定型接口
Predicate boolean test(T t):有参,但是返回值类型是固定的boolean
函数型接口
Function<T,R> R apply(T t)有参有返回值的抽象方法;