lambda常用方法
一:forEach() 循环遍历
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.forEach((x) -> System.out.println(x));
运行结果: 100 200 300 400 500
二:filte() 过滤
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().filter((x) -> x > 100).forEach((a)->System.out.print(a + " "));
运行结果: 200 300 400 500
三:lambda内部表达式中不能改变外部的变量
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
int sum = 10;
costBeforeTax.stream().forEach((x) -> sum +=x);
这种情况会报错
四:map() 将集合类中的元素进行转换
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().map(x -> x + 0.12 * x).forEach(x->System.out.print(x + " "));
运行结果:112.0 224.0 336.0 448.0 560.0
五:distinct() 对集合进行去重
List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> newlist = numbers.stream().distinct().collect(Collectors.toList());
System.out.print(newlist);
运行结果:[9, 10, 3, 4, 7]
distinct()之后是一个新集合。
2019年4月2日 17:05:44
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步