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());