当前位置: 首页 > news >正文

Lambda表达式的高级用法

今天来分享下Java的Lambda表达式,以及它的高级用法。

使用它可以提高代码的简洁度,使代码更优雅。

一、什么是lambda表达式

Lambda 表达式是 Java 8 引入的特性,用于简化匿名内部类的语法,使代码更简洁,尤其在处理函数式接口时。

二、Lambda表达式的12个高级用法

1. 集合遍历(foreach)

  • 普通写法
List<String> names = Arrays.asList("Alice", "Bob");
for(String name : names){System.out.println(name);
}
  • 优雅写法1
List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(name -> System.out.println(name));
  • 优雅写法2
names.forEach(System.out::println);

2. 条件过滤(filter)

  • 传统写法
List<String> filtered = new ArrayList<>();
for (String s : list) {if (s.startsWith("A")) {filtered.add(s);}
}
  • 优雅写法
List<String> filtered = list.stream().filter(s -> s.startsWith("A")).collect(Collectors.toList());

3. 映射转换(map)

  • 普通写法
List<String> names = Arrays.asList("Alice", "Bob");
List<Person> people = new ArrayList<>();
for (String name : names) {people.add(new Person(name));
}
  • 优雅写法
List<Person> people = names.stream().map(Person::new).collect(Collectors.toList());

4. 分组统计(groupingBy)

  • 普通写法
Map<String, List<Person>> peopleByCity = new HashMap<>();
for (Person person : people) {String city = person.getCity();if (!peopleByCity.containsKey(city)) {peopleByCity.put(city, new ArrayList<>());}peopleByCity.get(city).add(person);
}
  • 优雅写法
Map<String, List<Person>> peopleByCity = people.stream().collect(Collectors.groupingBy(Person::getCity));

5. 求和(reduce)

  • 普通写法
List<Integer> nums = Arrays.asList(1, 2, 3);
int sum = 0;
for (Integer n : nums) {sum += n;
}
  • 优雅写法
int sum = nums.stream().reduce(0, (a, b) -> a + b);

6. 排序(Comparator)

  • 普通写法
List<String> names = Arrays.asList("Bob", "Alice");
Collections.sort(names, new Comparator<String>() {@Overridepublic int compare(String a, String b) {return a.compareTo(b);}
});
  • 优雅写法1
names.sort((a, b) -> a.compareTo(b));
// 或方法引用:
  • 优雅写法2
names.sort(String::compareTo);

7. 替代匿名内部类(Runnable)

  • 普通写法
new Thread(new Runnable() {@Overridepublic void run() {System.out.println("Thread running");}
}).start();
  • 优雅写法
new Thread(() -> System.out.println("Thread running")).start();

8. 链式操作(多条件处理)

  • 普通写法
List<String> result = new ArrayList<>();
for (String name : names) {if (name.startsWith("A")) {result.add(name.toUpperCase());}
}
  • 优雅写法
names.stream().filter(name - > name.startsWith("A")).map(String::toUpperCase).collect(Collectors.toList());

9. 并行流处理(Parallel)

  • 普通写法
List<Integer> nums = Arrays.asList(1, 2, 3);ExecutorService executor = Executors.newFixedThreadPool(2);
for (Integer n : nums) {executor.submit(() -> process(n));
}
executor.shutdown();
  • 优雅写法
nums.parallelStream().forEach(n -> process(n));

10. 自定义函数式接口

  • 普通写法
// 定义函数式接口
@FunctionalInterface
interface MathOperation {int operate(int a, int b);
}MathOperation add = new MathOperation() {@Overridepublic int operate(int a, int b) {return a + b;}
};
  • 优雅写法
MathOperation add = (a, b) -> a + b;
MathOperation multiply = (a, b) -> a * b;

11. optional的链式操作

  • 普通写法
Optional<String> optional = Optional.of("test");if (optional.isPresent()) {String value = optional.get();System.out.println(value.toUpperCase());
}
  • 优雅写法
optional.map(String::toUpperCase).ifPresent(System.out::println);

12. 谓词组合(Predicate.and/or)

  • 普通写法
List<Integer> nums = Arrays.asList(1, 2, 3, 4);List<Integer> filtered = new ArrayList<>();
for (Integer n : nums) {if (n > 1 && n < 4) {filtered.add(n);}
}
  • 优雅写法
Predicate<Integer> greaterThan1 = n -> n > 1;
Predicate<Integer> lessThan4 = n -> n < 4;
List<Integer> filtered = nums.stream().filter(greaterThan1.and(lessThan4)).collect(Collectors.toList());

相关文章:

  • 华为云Flexus+DeepSeek征文|华为云 Dify LLM 平台单机部署教程:一键开启高效开发之旅
  • 软件设计师“数据流图”真题考点分析——求三连
  • Devicenet主转Profinet网关助力改造焊接机器人系统智能升级
  • springboot3+vue3融合项目实战-大事件文章管理系统-文章分类也表查询(条件分页)
  • 自建srs实时视频服务器支持RTMP推流和拉流
  • 什么是 Agent 的 Message
  • IP地址详解
  • OOP和软件设计中的五大核心设计原则——SOLID原则
  • 用户有一个Django模型没有设置主键,现在需要设置主键。
  • 几种超声波芯片的特点和对比
  • day019-特殊符号、正则表达式与三剑客
  • 谈谈 Kotlin 中的构造方法,有哪些注意事项?
  • 算子窗口操作
  • apache http client连接池实现原理
  • Android车载应用开发:Kotlin与Automotive OS深度实践
  • vue好用插件
  • 大语言模型与人工智能:技术演进、生态重构与未来挑战
  • Arthas:Java诊断利器实战指南
  • 网站制作公司哪家强?(2025最新版)
  • 【C语言】(10)—指针4
  • 上海数据开放网站建设/近期舆情热点事件
  • 个人网站也要备案吗/百度推广登陆首页
  • 广州建站方法/湖北百度seo
  • 免费源码html网站/短视频seo
  • 自己设计一个网站首页/google浏览器网页版
  • 东莞什么平台好做/广东seo网络培训