### Java函数式编程:Lambda表达式与Stream API应用指南
#### 一、Lambda表达式基础
1. 语法结构
```java
(parameters) -> expression
(parameters) -> { statements; }
```
2. 类型推断机制
- 编译器自动推断参数类型
- 可省略参数类型声明
- 单参数时可省略括号
3. 方法引用
- 静态方法引用:ClassName::staticMethod
- 实例方法引用:instance::method
- 构造方法引用:ClassName::new
#### 二、函数式接口
1. 核心接口
- `Function`:接受T类型参数,返回R类型结果
- `Consumer`:接受T类型参数,无返回值
- `Predicate`:接受T类型参数,返回boolean
- `Supplier`:无参数,返回T类型结果
2. 自定义函数式接口
```java
@FunctionalInterface
interface StringProcessor {
String process(String input);
}
```
#### 三、Stream API核心操作
1. 创建流
```java
// 从集合创建
List list = Arrays.asList(a, b, c);
Stream stream = list.stream();
// 从数组创建
String[] array = {a, b, c};
Stream stream = Arrays.stream(array);
// 静态工厂方法
Stream stream = Stream.of(a, b, c);
```
2. 中间操作
- filter(Predicate):过滤元素
- map(Function):元素转换
- sorted():排序
- distinct():去重
- limit(long):限制元素数量
3. 终端操作
- forEach(Consumer):遍历消费
- collect(Collector):收集结果
- reduce(BinaryOperator):归约操作
- count():统计元素数量
- anyMatch(Predicate):是否存在匹配元素
#### 四、实践应用示例
1. 数据处理
```java
List names = Arrays.asList(Alice, Bob, Charlie, David);
// 过滤并转换
List result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
```
2. 数值计算
```java
List numbers = Arrays.asList(1, 2, 3, 4, 5);
// 求和
int sum = numbers.stream()
.reduce(0, Integer::sum);
// 求最大值
Optional max = numbers.stream()
.max(Integer::compareTo);
```
3. 分组统计
```java
List people = Arrays.asList(
new Person(Alice, 25),
new Person(Bob, 30),
new Person(Charlie, 25)
);
// 按年龄分组
Map> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
```
#### 五、性能优化建议
1. 优先使用基本类型特化流
- IntStream、LongStream、DoubleStream
- 避免装箱拆箱开销
2. 合理使用并行流
- 数据量较大时考虑parallelStream()
- 注意线程安全问题
3. 避免在流中修改外部状态
- 保持无状态操作
- 确保操作是纯函数
#### 六、异常处理策略
1. 受检异常处理
```java
List filePaths = Arrays.asList(file1.txt, file2.txt);
List contents = filePaths.stream()
.map(path -> {
try {
return Files.readString(Paths.get(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList());
```
2. 使用工具方法封装异常处理
```java
@FunctionalInterface
interface ThrowingFunction {
R apply(T t) throws Exception;
static Function unchecked(ThrowingFunction f) {
return t -> {
try {
return f.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
```
#### 七、最佳实践总结
1. 代码可读性
- 保持Lambda表达式简洁
- 复杂逻辑提取为独立方法
- 使用方法引用提升可读性
2. 性能考量
- 避免在流链中执行昂贵操作
- 合理选择顺序流与并行流
- 及时关闭IO相关流
3. 调试技巧
- 使用peek()方法进行调试
- 分步执行流操作
- 合理使用日志输出
通过合理运用Lambda表达式和Stream API,可以显著提升Java代码的简洁性和可维护性,同时保持较好的执行效率。在实际开发中应根据具体场景选择合适的使用方式,平衡代码可读性与性能需求。

被折叠的 条评论
为什么被折叠?



