Java优雅编程之Lambda表达式(精简)
话不多说奔主题,精神抖擞就是干!
定义集合变量
List<Integer> lst = Arrays.asList(1, 2, 3);
下面直抒胸臆👇
1. 循环打印
lst.forEach(x -> System.out.println(x));
或
lst.forEach(System.out::println);
输出:
1
2
3
2. 对集合内元素值+1
Stream<Integer> st = lst.stream().map(x-> x + 1);
st.forEach(x -> System.out.println(x));
输出:
2
3
4
3. 对集合内元素过滤,保留值大于2的
Stream<Integer> st = lst.stream().filter(x-> x > 2);
st.forEach(x -> System.out.println(x));
输出:
3
4. 对集合内元素求和,传入一个方法体(效果同函数式接口Predicate)
Optional<Integer> op = lst.stream().reduce((sum, x)-> sum.sum(sum, x));
System.out.println(op.get());
输出:
6
*5. 升阶,与函数式接口结合使用
定义函数式接口
@FunctionalInterface
public Interface MyFunction{
public void sout(String msg);
}
两种实现方法
public void main(String[] args) {
//以前
MyFunction mf = new MyFunction() {
@Override
public void sout(String msg) { System.out.println(msg); }
};
//现在
MyFunction mf = msg->System.out.println(msg);
//调用
mf.sout("我真是个天才");
}
输出:
我真是个天才
*6. 二阶,与含有Predicate入参的函数式接口结合使用
目的:将条件表达式抽离出来作为入参,方便外部调用者注入自己的逻辑。
定义函数式接口
@FunctionalInterface
public Interface MyFunction {
public void sout(List<Integer> lst, Predicate<Integer> condition);
}
实现方法
public void main(String[] args) {
//Lambda表达式实现
MyFunction mf = (lst, condition)-> lst.stream().filter(condition).forEach(System.out::println);
//调用
mf.sout(Arrays.asList(1, 2, 3), x-> x > 2);
}
输出:
3
*7. 三阶,改用泛型与含有Predicate入参的函数式接口结合使用
定义函数式接口
@FunctionalInterface
public Interface MyFunction<T> {
public void sout(List<T> lst, Predicate<T> condition);
}
实现方法
public void main(String[] args) {
//Lambda表达式实现
MyFunction<Integer> mf = (lst, condition)-> lst.stream().filter(condition).forEach(System.out::println);
//调用
mf.sout(Arrays.asList(1, 2, 3), x-> x > 2);
}
输出:
3
欢迎看官儿们留言补充和指正,谢谢下次见!

浙公网安备 33010602011771号