衷于栖
  • 衷于栖
  • 首页
  • 归档
  • 关于

Image
Profile Picture

衷于栖

自由开发者

分类目录

三维技术4 介绍2 应用1 异常1 技术笔记17 游戏2 源码解读3 管理5 读书笔记3 车联网3 转载11 随笔3

热门标签

  • GIT
  • 工作流指南
  • docker
  • SCRUM
  • JT808
  • 百度地图
  • 狼人杀
  • 模型数据结构
  • 敏捷
  • 扩展
  • 学习WEBGL系列
  • 可维护
  • GlTF
  • CentOS
  • 高德地图
  • 集中式
  • 郭麒麟
  • 郭德纲
  • 进阶
  • 路由节点编辑器

微信订阅

Image

友情链接

王海达博客 Steve Yegge Debug 客栈 Codelei's Blog 笛卡尔积 Java九点半课堂 薛定喵君

【JAVA】JDK8一些语言特性以及新增API记录

2019-01-14     技术笔记


涵盖:函数式编程、lambda表达式、接口新特性、api内函数接口、级联表达式和柯里化、Stream流编程

函数式编程

函数式编程不需要关注实现的细节。

假如想要获取数组中数值的最小值,按照常规方式,需要使用排序或者查找算法,并且这个算法需要自己实现。在函数式编程中就会隐藏细节。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 获取最小值
public static int min(int[] arr){
// 获取最小值的实现
}

public static void main(String[] args){
int[] arr = new int[]{12,8,45,444,21};

int min_classic = min(arr);

// 而函数编程则是这样:
int min_func = IntStream.of(arr).min().getAsInt();
}

lambda

实现函数接口(只有一个方法的接口)

1
Runnable runnable = () -> System.out.println("lambda");

方法引用

1
2
3
// 方法引用
Consumer<String> consumer = Systme.out::println;
// 构造方法引用 使用 Object::new

接口新特性

新注解: @FunctionInterface 用于注解函数接口

默认方法

1
2
3
4
5
6
7
8
9
@FunctionInterface
interface InterfaceDemo{

int plus(int x, int y);

default int add(int x, int y){
return x + y;
}
}

api内函数接口

  • Predicate 断言
  • Consumer 消费一个数据
  • Function<T, R> 输入T输出R的函数
  • Supplier 提供一个数据
  • UnaryOperator 一元函数(输出输入类型相同)
  • BiFunction<T, U, R> 2个输入的函数
  • BinaryOperator 二元函数(输出输入类型相同)

级联表达式和柯里化

级联表达式

1
2
3
4
Function<Integer, Function<Integer, Function<Integer, Integer>>> func = x -> y -> z -> x + y + z;

func.apply(1).apply(2).apply(3);
// 6

柯里化:把多个参数的函数转化为只有一个参数的函数,用于标准化函数。

Stream流编程

创建

1
2
3
4
5
6
Collection.stream
Collection.parallelStream
Arrays.stream
IntStream/LongStream.range/rangeClosed
Random.ins/longs/doubles
Stream.generate/iterate

中间操作

1
2
3
4
5
6
7
8
9
10
11
// 无状态
map/mapToXxx
flatMap/flatMapToXxx
filter
peek
unordered

// 有状态
distinct
sorted
limit/skip

终止操作

1
2
3
4
5
6
7
8
9
// 非短路操作
forEach/forEachOrdered
collect/toArray
reduce
min/max/count

// 短路操作
findFirst/findAny
allMatch/anyMatch/noneMatch

并行流

1
2
3
4
5
6
7
8
9
// 并行
parallel()
// 串行
sequential()

// 自定义线程池
ForkJoinPool pool = new ForkJoinPool(20);
pool.submit(() -> stream.parallel().count());
pool.shutdown();

收集器

1
2
3
4
5
6
7
8
// 列表
stream().collect(Collectors.toList());
// 统计
stream().collect(Collectors.summarizingInt(Student::getAge));
// 分块
stream().collect(Collectors.partitioningBy(s -> s.getGender() == Gender.MALE));
// 分组
stream().collect(Collectors.groupBy(Student::getGrade));
#JDK8 #JAVA #语言特性

Copyright © 2021 zhoyq.com. All rights reserved.

京ICP备 17068495号-1