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>() {
    @Override
    public 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() {
    @Override
    public 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() {
    @Override
    public 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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coding侠客

一起充电,一起成长。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值