如何使用Lambda表达式简化Stream API的代码?代码举例讲解

Lambda 表达式和 Stream API 天生就配合得非常好。Stream API 提供了各种针对数据集合的扣慕操作,而 Lambda 表达式正好提供了精简的实现逻辑,两者搭配可以大大简化代码。

举个例子,假设我们有一个 Person 列表,要按年龄排序并过滤出年龄大于30的人:
没有 Stream API 和 Lambda 时,代码如下:

List<Person> people = Arrays.asList(
    new Person("John", 30),
    new Person("Amy", 12), 
    new Person("Lisa", 55)
);  

List<Person> result = new ArrayList<>();
for (Person person : people) {
    if (person.getAge() > 30) {
        result.add(person); 
    } 
}
Collections.sort(result, new Comparator<Person>() {
    public int compare(Person a, Person b) {
        return a.getAge() - b.getAge(); 
    } 
});

使用 Stream API 和 Lambda 后,代码变为:

List<Person> result = people.stream()
                            .filter(p -> p.getAge() > 30)
                            .sorted((a, b) -> a.getAge() - b.getAge())
                            .collect(Collectors.toList()); 

从上面两个示例可以明显看出,Lambda 表达式和 Stream API 结合让代码显得更简洁和优雅:

  1. 没有显式创建集合和 for 循环,直接用 filter 进行过滤。
  2. 没有创建匿名 Comparator 类,直接在 sorted 中传入 Lambda 表达式。
  3. 逻辑更简洁清晰,不同操作用 . 链接在一起。

此外,Stream API 不但可以用于 Collection,还可以用于数组、磁盘文件等。它提供了一套完整的集合操作方法,配合 Lambda 表达式可以实现非常强大而优雅的功能。