用Stream来优化老代码,瞬间干净优雅了!
Java技术江湖
共 4405字,需浏览 9分钟
· 2022-01-11
点击上方“Java技术江湖”,选择“设为星标”
回复”666“获取全网最热的Java核心知识点整理
Java8 的新特性主要是 Lambda 表达式和流,当流和 Lambda 表达式结合起来一起使用时,因为流申明式处理数据集合的特点,可以让代码变得简洁易读。
01 流如何简化代码
筛选出卡路里小于 400 的菜肴 对筛选出的菜肴进行一个排序 获取排序后菜肴的名字
Dish.java
(菜肴)public class Dish {
private String name;
private boolean vegetarian;
private int calories;
private Type type;
// getter and setter
}
private List beforeJava7(List {dishList)
ListlowCaloricDishes = new ArrayList<>();
//1.筛选出卡路里小于400的菜肴
for (Dish dish : dishList) {
if (dish.getCalories() < 400) {
lowCaloricDishes.add(dish);
}
}
//2.对筛选出的菜肴进行排序
Collections.sort(lowCaloricDishes, new Comparator() {
@Override
public int compare(Dish o1, Dish o2) {
return Integer.compare(o1.getCalories(), o2.getCalories());
}
});
//3.获取排序后菜肴的名字
ListlowCaloricDishesName = new ArrayList<>();
for (Dish d : lowCaloricDishes) {
lowCaloricDishesName.add(d.getName());
}
return lowCaloricDishesName;
}
private List afterJava8(List {dishList)
return dishList.stream()
.filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
.sorted(comparing(Dish::getCalories)) //根据卡路里进行排序
.map(Dish::getName) //提取菜肴名称
.collect(Collectors.toList()); //转换为List
}
对数据库查询到的菜肴根据菜肴种类进行分类,返回一个 Map
的结果
private static Map > beforeJDK8(List dishList) {
Map> result = new HashMap<>();
for (Dish dish : dishList) {
//不存在则初始化
if (result.get(dish.getType())==null) {
Listdishes = new ArrayList<>();
dishes.add(dish);
result.put(dish.getType(), dishes);
} else {
//存在则追加
result.get(dish.getType()).add(dish);
}
}
return result;
}
private static Map > afterJDK8(List dishList) {
return dishList.stream().collect(groupingBy(Dish::getType));
}
02 什么是流
03 如何生成流
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Streamstream = integerList.stream();
int[] intArr = new int[]{1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArr);
Arrays.stream
方法生成流,并且该方法生成的流是数值流【即 IntStream
】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。mapToInt
、mapToDouble
、mapToLong
三种方式将对象流【即 Stream】转换成对应的数值流,同时提供了 boxed
方法将数值流转换为对象流Stream stream = Stream.of(1, 2, 3, 4, 5);
of
方法生成流,通过 Stream 的 empty
方法可以生成一个空流Stream lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())
Stream stream = Stream.iterate(0, n -> n + 2).limit(5);
Stream stream = Stream.generate(Math::random).limit(5);
04 流的操作类型
中间操作
filter
、map
等终端操作
count
、collect
等05 流使用
中间操作
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Streamstream = integerList.stream().filter(i -> i > 3);
filter
方法进行条件筛选,filter
的方法参数为一个条件List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Streamstream = integerList.stream().distinct();
distinct
方法快速去除重复的元素List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Streamstream = integerList.stream().limit(3);
limit
方法指定返回流的个数,limit 的参数值必须 >=0,否则将会抛出异常List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Streamstream = integerList.stream().skip(2);
skip
方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为 2,3,4,5,skip
的参数值必须 >=0,否则将会抛出异常List stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");
Streamstream = stringList.stream().map(String::length);
复制代码
map
方法可以完成映射,该例子完成中 String -> Integer
的映射,之前上面的例子通过 map
方法完成了 Dish->String
的映射List wordList = Arrays.asList("Hello", "World");
ListstrList = wordList.stream()
.map(w -> w.split(" "))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
map(w -> w.split(" "))
的返回值为 Stream
,我们想获取 Stream
,可以通过 flatMap
方法完成 Stream ->Stream
的转换allMatch
匹配所有List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println("值都大于3");
}
anyMatch
匹配其中一个List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println("存在大于3的值");
}
for (Integer i : integerList) {
if (i > 3) {
System.out.println("存在大于3的值");
break;
}
}
noneMatch
全部不匹配List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println("值都小于3");
}
终端操作
count
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
findFirst
查找第一个//查找到第一个大于 3 的元素并打印
ListintegerList = Arrays.asList(1, 2, 3, 4, 5);
Optionalresult = integerList.stream().filter(i -> i > 3).findFirst();
findAny
随机查找一个List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optionalresult = integerList.stream().filter(i -> i > 3).findAny();
findAny
方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和 findFirst
方法结果一样。提供 findAny
方法是为了更好的利用并行流,findFirst
方法在并行上限制更多int sum = 0;
for (int i : integerList) {
sum += i;
}
reduce
进行处理int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
int sum = integerList.stream().reduce(0, Integer::sum);
reduce
接受两个参数,一个初始值这里是 0,一个 BinaryOperator accumulator
来将两个元素结合起来产生一个新值,Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optionalmax = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();
min
获取流中最小值,max
获取流中最大值,方法参数为 Comparator super T> comparator
Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optionalmax = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
minBy
获取流中最小值,maxBy
获取流中最大值,方法参数为 Comparator super T> comparator
reduce
获取最小最大值Optional min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optionalmax = menu.stream().map(Dish::getCalories).reduce(Integer::max);
复制代码
07 总结
Maven入门,读完这篇就够了
开源困境:Log4j2 维护者发声:没有工资,还要挨骂!!
面试官问:MySQL的自增 ID 用完了,怎么办?
关注公众号【Java技术江湖】后回复“PDF”即可领取200+页的《Java工程师面试指南》
强烈推荐,几乎涵盖所有Java工程师必知必会的知识点,不管是复习还是面试,都很实用。
评论
用 Shader 实现旗帜飘扬动画效果
我觉得对于刚入门 3D 编程的朋友来说,如果能够完成代码创建模型数据->创建材质->编写Shader动画这一系列,想必会有满满的成就感。今天就用 Cocos Creator 的 utils.MeshUtils.createMesh 接口,带大家感受一下这个流程。这个流程不仅可以用于新手学
COCOS
2
雷军辟谣了!不是高考状元,卡里也没有冰冷的 40 亿
架构师大咖
架构师大咖,打造有价值的架构师交流平台。分享架构师干货、教程、课程、资讯。架构师大咖,每日推送。
公众号该公众号已被封禁最近很火的雷军简历,听说落魄时卡里只有冰冷的 40
源码共读
0
警报炸锅了,FastJson 又立功了。。
往期热门文章:1、一个小公司的技术开发心酸事(已倒闭)2、JetBrains 如何看待自己的软件在中国被频繁破解?3、程序员因Bug被要求归还4万多年终奖,网友:不还!4、一套万能通用的异步处理方案5、微服务全做错了!谷歌提出新方法,成本直接降9倍!线上事故回顾前段时间新增一个特别简单的功能,晚上上
Java后端技术
1
只要状态对了,事儿也就顺了
卖鸡蛋思维,适合各行各业的套用思维没钱时,牢记卖鸡蛋思维。 请一定耐心看完,成就不一样的你自己。When there‘s no money,Remember the thought of selling eggs.卖鸡蛋思维强调的是商业和经济思维的重要性,从商和创业都应该具备这样的思
小Q聊产品
0
我用这10招,能减少了80%的BUG
将Python客栈设为“星标⭐”第一时间收到最新资讯前言对于大部分程序员来说,主要的工作时间是在开发和修复BUG。有可能修改了一个BUG,会导致几个新BUG的产生,不断循环。那么,有没有办法能够减少BUG,保证代码质量,提升工作效率?答案是肯定的。如果能做到,我们多出来的时间,多摸点鱼,做点自己喜欢
Python客栈
0
上门按摩的女技师们,要IPO了
不刮骨疗毒,怎么两袖清风?冲击万店,汉堡界能跑出下一个蜜雪冰城吗?拥有2.5万上门按摩女技师的东郊到家,要IPO了。消息源于东郊到家创始人汤帆在重庆首届O2O行业发展大会上的发言。汤帆表示,截至2023年底,东郊到家完成了部分IPO的规划实施及合规准备工作,并称东郊委托的上市中介机构是第一梯队的品牌
亿欧网
0
十万亿智慧养老市场,走到哪一步了?
《2024年智慧康养平台模式发展研究报告》即将发布。文|王菲当前,中国人口老龄化程度不断加剧,为了应对日益凸显的养老难题,构建多层次养老服务体系成为社会关注的热点。根据最新发布的《中华人民共和国2023年国民经济和社会发展统计公报》显示,我国60岁及以上的老年人口数量已达到2.97亿,占全国总人口的
亿欧网
0
啤酒厂,造了一台“诺基亚”
今天再聊个好玩的 你们都喝过喜力啤酒吧?就是Heineken他们家也出手机了长这样喜力啤酒这几天和 HMD 以及美国零售商 Bodega 合作推出了一款名为「The Boring Phone」的翻盖机看到HMD你们应该就知道,其实就是诺基亚啦 这个造型,我一眼就认出是你啦!这款手机采用透明
放毒
3