用Stream来优化老代码,瞬间干净优雅了!
泥瓦匠BYSocket
共 4461字,需浏览 9分钟
· 2022-03-03
不点蓝字关注,我们哪来故事?
一个指导程序员进入大公司/独角兽 的精品社群,致力于分享职场达人的专业打法,包括「学习路线+简历模板+实习避坑+笔试面试+试用转正+升职加薪+跳槽技巧」。
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 总结
推荐
评论
老爸嘲讽我了,写破代码一年就挣十几万,他在工地带50个工人,一个月光人头费就3万,让我滚回去跟他干!
点击上方 "大数据肌肉猿"关注, 星标一起成长点击下方链接,进入高质量学习交流群今日更新| 1052个转型案例分享-大数据交流群来自:网络,侵删有个网友的父亲是做工程的,天天就嘲笑他,说他天天写着破代码有啥用,一年就拿个十多万的死工资,然后告诉他自己在工地里面带了50个工人,一个月能抽三万
程序源代码
0
微软开源MS-DOS操作系统源码,冲到GitHub第一了!
大家好,我是轩辕。这两天逛GitHub的时候,突然发现一个叫 MS-DOS的项目冲到Trending榜首了!定睛一看,微软官方啊,搜了一下才知道,原来前两天,微软把MS-DOS 4.0系统开源了!关于这个系统,估计现在很多程序员都不知道了,或者只在古老的教科书上看过这玩意儿。MS-DOS,全称为Mi
编程技术宇宙
6
多人同时导出 Excel 干崩服务器!新来的阿里大佬给出的解决方案太优雅了!
点击关注公众号,Java 干货及时推送↓推荐阅读:面试辅导,我们出大成果了!来源:juejin.cn/post/7259249904777838629前言 业务诉求:考虑到数据库数据日渐增多,导出会有全量数据的导出,多人同时导出可以会对服务性能造成影响,导出涉及到mysql查询的io操作,
Java技术栈
1
今年后端爆了???
大家好,我是二哥呀。每次登录牛客,看到最多的就是各种 Java 后端岗位的喜讯,美团 OC了、快手 OC 了、就连腾讯 OC 的都是 Java 岗,我怀疑牛客是不是给我打了“只报喜不报忧”的标签?星球里也有不少球友给我发来喜讯,难道说每年都在凉凉的 Java 后端又承担起了就业的重任?!不可能,绝对
沉默王二
3
Datawhale来“瓜大”(西工大🫡)啦!
Datawhale线下 主办方:Datawhale团队西北工业大学(Northwestern Polytechnical University)简称“西工大”,位于陕西省会西安市,直属中华人民共和国工业和信息化部,是中国唯一一所以同时发展航空、航天、航海(三航)工程教育和科学研
Datawhale
1
大厂都在用的 Git 代码管理规范 !
👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0 版本完结啦, 演示链接:http://116.62.199.48/ ,新项目正在酝酿中
小哈学Java
2
这五款牛逼的 IDEA 插件,堪称代码质量检查利器!
来源:blog.csdn.net/a745233700?type=blog一、Alibaba Java Coding Guidelines二、CheckStyle:三、PMD四、FindBugs:五、SonarLint:总结随着业务的发展,系统会越来越庞大,原本简单稳定的功能,可能在不断迭代后复杂度
码农突围
0
接口响应慢?那是你没用 CompletableFuture 来优化!
来源:blog.csdn.net/qq_43372633/article/details/130814200👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0
小哈学Java
3