首页 > 其他分享 >用Stream来优化老代码,就是爽

用Stream来优化老代码,就是爽

时间:2022-10-11 23:01:48浏览次数:34  
标签:Stream stream Arrays integerList 代码 List Dish 优化

Java8 的新特性主要是 Lambda 表达式和流,当流和 Lambda 表达式结合起来一起使用时,因为流申明式处理数据集合的特点,可以让代码变得简洁易读。
01 流如何简化代码如果有一个需求,需要对数据库查询到的菜肴进行一个处理:筛选出卡路里小于 400 的菜肴对筛选出的菜肴进行一个排序获取排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
}
Java8 以前的实现方式private List beforeJava7(List dishList) {
List lowCaloricDishes = new ArrayList<>();//1.筛选出卡路里小于400的菜肴
for (Dish dish : dishList) {
if (dish.getCalories() < 400) {
lowCaloricDishes.add(dish);
}
}

//2.对筛选出的菜肴进行排序
Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
@Override
public int compare(Dish o1, Dish o2) {
return Integer.compare(o1.getCalories(), o2.getCalories());
}
});

//3.获取排序后菜肴的名字
List<String> lowCaloricDishesName = new ArrayList<>();
for (Dish d : lowCaloricDishes) {
lowCaloricDishesName.add(d.getName());
}

return lowCaloricDishesName;}
Java8 之后的实现方式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
}
不拖泥带水,一气呵成,原来需要写 24 代码实现的功能现在只需 5 行就可以完成了高高兴兴写完需求这时候又有新需求了,新需求如下:
对数据库查询到的菜肴根据菜肴种类进行分类,返回一个 Map<Type, List> 的结果
这要是放在 JDK8 之前肯定会头皮发麻
Java8 以前的实现方式
private static Map<Type, List> beforeJDK8(List dishList) {
Map<Type, List> result = new HashMap<>();for (Dish dish : dishList) {
//不存在则初始化
if (result.get(dish.getType())==null) {
List<Dish> dishes = new ArrayList<>();
dishes.add(dish);
result.put(dish.getType(), dishes);
} else {
//存在则追加
result.get(dish.getType()).add(dish);
}
}

return result;}
还好 JDK8 有 Stream,再也不用担心复杂集合处理需求Java8 以后的实现方式
private static Map<Type, List> afterJDK8(List dishList) {
return dishList.stream().collect(groupingBy(Dish::getType));
}
又是一行代码解决了需求,忍不住大喊 Stream API 牛批 看到流的强大功能了吧,接下来将详细介绍流02 什么是流
流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算。03 如何生成流
生成流的方式主要有五种:1.通过集合生成,应用中最常用的一种
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Stream stream = integerList.stream();
通过集合的 stream 方法生成流2.通过数组生成
int[] intArr = new int[]{1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArr);
通过 Arrays.stream 方法生成流,并且该方法生成的流是数值流【即 IntStream 】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。Stream API 提供了mapToInt、mapToDouble、mapToLong三种方式将对象流【即 Stream】转换成对应的数值流,同时提供了 boxed 方法将数值流转换为对象流
3.通过值生成
Stream stream = Stream.of(1, 2, 3, 4, 5);
通过 Stream 的 of 方法生成流,通过 Stream 的 empty 方法可以生成一个空流4.通过文件生成
Stream lines = Files.lines(Paths.get(“data.txt”), Charset.defaultCharset())
通过 Files.line 方法得到一个流,并且得到的每个流是给定文件中的一行5.通过函数生成 提供了 iterate 和 generate 两个静态方法从函数中生成流
iterator
Stream stream = Stream.iterate(0, n -> n + 2).limit(5);
iterate 方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为 iterator 生成的流为无限流,通过 limit 方法对流进行了截断,只生成 5 个偶数generator
Stream stream = Stream.generate(Math::random).limit(5);
generate 方法接受一个参数,方法参数类型为 Supplier,由它为流提供值。generate 生成的流也是无限流,因此通过 limit 对流进行了截断04 流的操作类型
流的操作类型主要分为两种: 中间操作、终端操作。中间操作
一个流可以后面跟随零个或多个中间操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的,仅仅调用到这类方法,并没有真正开始流的遍历,真正的遍历需等到终端操作时,常见的中间操作有下面即将介绍的 filter、map 等终端操作
一个流有且只能有一个终端操作,当这个操作执行后,流就被关闭了,无法再被操作,因此一个流只能被遍历一次,若想在遍历需要通过源数据在生成流。终端操作的执行,才会真正开始流的遍历。如下面即将介绍的 count、collect 等05 流使用
流的使用将分为终端操作和中间操作进行介绍中间操作
filter 筛选List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().filter(i -> i > 3);
通过使用 filter 方法进行条件筛选,filter 的方法参数为一个条件distinct 去除重复元素
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().distinct();
通过 distinct 方法快速去除重复的元素limit 返回指定流个数
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().limit(3);
通过 limit 方法指定返回流的个数,limit 的参数值必须 >=0,否则将会抛出异常skip 跳过流中的元素
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().skip(2);
通过 skip 方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为 2,3,4,5,skip 的参数值必须 >=0,否则将会抛出异常map 流映射
所谓流映射就是将接受的元素映射成另外一个元素
List stringList = Arrays.asList(“Java 8”, “Lambdas”, “In”, “Action”);
Stream stream = stringList.stream().map(String::length);
复制代码
通过 map 方法可以完成映射,该例子完成中 String -> Integer 的映射,之前上面的例子通过 map 方法完成了 Dish->String 的映射flatMap 流转换
将一个流中的每个值都转换为另一个流
List wordList = Arrays.asList(“Hello”, “World”);
List strList = wordList.stream()
.map(w -> w.split(" “))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
map(w -> w.split(” ")) 的返回值为 Stream<String[]>,我们想获取 Stream,可以通过 flatMap 方法完成 Stream ->Stream 的转换元素匹配
提供了三种匹配方式:
1.allMatch 匹配所有
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println(“值都大于3”);
}
2.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;
}
}
3.noneMatch 全部不匹配List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println(“值都小于3”);
}
通过 noneMatch 方法实现终端操作
统计流中元素个数通过 count
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
通过使用 count 方法统计出流中元素个数通过 counting
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
最后一种统计元素个数的方法在与 collect 联合使用的时候特别有用查找
提供了两种查找方式
1、findFirst 查找第一个
//查找到第一个大于 3 的元素并打印
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findFirst();
2、findAny 随机查找一个List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findAny();
通过 findAny 方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和 findFirst 方法结果一样。提供 findAny 方法是为了更好的利用并行流,findFirst 方法在并行上限制更多reduce 将流中的元素组合起来
假设我们对一个集合中的值进行求和
JDK8 之前:
int sum = 0;
for (int i : integerList) {
sum += i;
}
JDK8 之后通过 reduce 进行处理int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
一行就可以完成,还可以使用方法引用简写成:int sum = integerList.stream().reduce(0, Integer::sum);
reduce 接受两个参数,一个初始值这里是 0,一个 BinaryOperator accumulator 来将两个元素结合起来产生一个新值,另外, reduce 方法还有一个没有初始化值的重载方法
获取流中最小最大值
通过 min/max 获取最小最大值
Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional max = 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通过 minBy/maxBy 获取最小最大值
Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional max = 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);
Optional max = menu.stream().map(Dish::getCalories).reduce(Integer::max);
复制代码
07 总结
这篇文章主要介绍了 Stream API 的相关使用,从文中所列举的例子可以看出:通过使用 Stream API 可以简化代码,同时还提高了代码可读性。所以,赶紧在项目里用起来吧!序后菜肴的名字Dish.java(菜肴)public class Dish { private String name; private boolean vegetarian; private int calories; private Type type; // getter and setter}Java8 以前的实现方式private List beforeJava7(List dishList) { List lowCaloricDishes = 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.获取排序后菜肴的名字 List lowCaloricDishesName = new ArrayList<>(); for (Dish d : lowCaloricDishes) { lowCaloricDishesName.add(d.getName()); } return lowCaloricDishesName;}Java8 之后的实现方式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}不拖泥带水,一气呵成,原来需要写 24 代码实现的功能现在只需 5 行就可以完成了高高兴兴写完需求这时候又有新需求了,新需求如下:对数据库查询到的菜肴根据菜肴种类进行分类,返回一个 Map<Type, List> 的结果这要是放在 JDK8 之前肯定会头皮发麻Java8 以前的实现方式private static Map<Type, List> beforeJDK8(List dishList) { Map<Type, List> result = new HashMap<>(); for (Dish dish : dishList) { //不存在则初始化 if (result.get(dish.getType())==null) { List dishes = new ArrayList<>(); dishes.add(dish); result.put(dish.getType(), dishes); } else { //存在则追加 result.get(dish.getType()).add(dish); } } return result;}还好 JDK8 有 Stream,再也不用担心复杂集合处理需求Java8 以后的实现方式private static Map<Type, List> afterJDK8(List dishList) { return dishList.stream().collect(groupingBy(Dish::getType));}又是一行代码解决了需求,忍不住大喊 Stream API 牛批 看到流的强大功能了吧,接下来将详细介绍流02 什么是流流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算。03 如何生成流生成流的方式主要有五种:1.通过集合生成,应用中最常用的一种List integerList = Arrays.asList(1, 2, 3, 4, 5);Stream stream = integerList.stream();通过集合的 stream 方法生成流2.通过数组生成int[] intArr = new int[]{1, 2, 3, 4, 5};IntStream stream = Arrays.stream(intArr);通过 Arrays.stream 方法生成流,并且该方法生成的流是数值流【即 IntStream 】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。Stream API 提供了mapToInt、mapToDouble、mapToLong三种方式将对象流【即 Stream】转换成对应的数值流,同时提供了 boxed 方法将数值流转换为对象流3.通过值生成Stream stream = Stream.of(1, 2, 3, 4, 5);通过 Stream 的 of 方法生成流,通过 Stream 的 empty 方法可以生成一个空流4.通过文件生成Stream lines = Files.lines(Paths.get(“data.txt”), Charset.defaultCharset())通过 Files.line 方法得到一个流,并且得到的每个流是给定文件中的一行5.通过函数生成 提供了 iterate 和 generate 两个静态方法从函数中生成流iteratorStream stream = Stream.iterate(0, n -> n + 2).limit(5);iterate 方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为 iterator 生成的流为无限流,通过 limit 方法对流进行了截断,只生成 5 个偶数generatorStream stream = Stream.generate(Math::random).limit(5);generate 方法接受一个参数,方法参数类型为 Supplier,由它为流提供值。generate 生成的流也是无限流,因此通过 limit 对流进行了截断04 流的操作类型流的操作类型主要分为两种: 中间操作、终端操作。中间操作一个流可以后面跟随零个或多个中间操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的,仅仅调用到这类方法,并没有真正开始流的遍历,真正的遍历需等到终端操作时,常见的中间操作有下面即将介绍的 filter、map 等终端操作一个流有且只能有一个终端操作,当这个操作执行后,流就被关闭了,无法再被操作,因此一个流只能被遍历一次,若想在遍历需要通过源数据在生成流。终端操作的执行,才会真正开始流的遍历。如下面即将介绍的 count、collect 等05 流使用流的使用将分为终端操作和中间操作进行介绍中间操作filter 筛选List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream stream = integerList.stream().filter(i -> i > 3);通过使用 filter 方法进行条件筛选,filter 的方法参数为一个条件distinct 去除重复元素List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream stream = integerList.stream().distinct();通过 distinct 方法快速去除重复的元素limit 返回指定流个数List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream stream = integerList.stream().limit(3);通过 limit 方法指定返回流的个数,limit 的参数值必须 >=0,否则将会抛出异常skip 跳过流中的元素List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream stream = integerList.stream().skip(2);通过 skip 方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为 2,3,4,5,skip 的参数值必须 >=0,否则将会抛出异常map 流映射所谓流映射就是将接受的元素映射成另外一个元素List stringList = Arrays.asList(“Java 8”, “Lambdas”, “In”, “Action”);Stream stream = stringList.stream().map(String::length);复制代码通过 map 方法可以完成映射,该例子完成中 String -> Integer 的映射,之前上面的例子通过 map 方法完成了 Dish->String 的映射flatMap 流转换将一个流中的每个值都转换为另一个流List wordList = Arrays.asList(“Hello”, “World”);List strList = wordList.stream() .map(w -> w.split(" “)) .flatMap(Arrays::stream) .distinct() .collect(Collectors.toList());map(w -> w.split(” ")) 的返回值为 Stream<String[]>,我们想获取 Stream,可以通过 flatMap 方法完成 Stream ->Stream 的转换元素匹配提供了三种匹配方式:1.allMatch 匹配所有List integerList = Arrays.asList(1, 2, 3, 4, 5);if (integerList.stream().allMatch(i -> i > 3)) { System.out.println(“值都大于3”);}2.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; }}3.noneMatch 全部不匹配List integerList = Arrays.asList(1, 2, 3, 4, 5);if (integerList.stream().noneMatch(i -> i > 3)) { System.out.println(“值都小于3”);}通过 noneMatch 方法实现终端操作统计流中元素个数通过 countList integerList = Arrays.asList(1, 2, 3, 4, 5);Long result = integerList.stream().count();通过使用 count 方法统计出流中元素个数通过 countingList integerList = Arrays.asList(1, 2, 3, 4, 5);Long result = integerList.stream().collect(counting());最后一种统计元素个数的方法在与 collect 联合使用的时候特别有用查找提供了两种查找方式1、findFirst 查找第一个//查找到第一个大于 3 的元素并打印List integerList = Arrays.asList(1, 2, 3, 4, 5);Optional result = integerList.stream().filter(i -> i > 3).findFirst();2、findAny 随机查找一个List integerList = Arrays.asList(1, 2, 3, 4, 5);Optional result = integerList.stream().filter(i -> i > 3).findAny();通过 findAny 方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和 findFirst 方法结果一样。提供 findAny 方法是为了更好的利用并行流,findFirst 方法在并行上限制更多reduce 将流中的元素组合起来假设我们对一个集合中的值进行求和JDK8 之前:int sum = 0;for (int i : integerList) {sum += i;}JDK8 之后通过 reduce 进行处理int sum = integerList.stream().reduce(0, (a, b) -> (a + b));一行就可以完成,还可以使用方法引用简写成:int sum = integerList.stream().reduce(0, Integer::sum);reduce 接受两个参数,一个初始值这里是 0,一个 BinaryOperator accumulator 来将两个元素结合起来产生一个新值,另外, reduce 方法还有一个没有初始化值的重载方法获取流中最小最大值通过 min/max 获取最小最大值Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);Optional max = 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通过 minBy/maxBy 获取最小最大值Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));Optional max = 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);Optional max = menu.stream().map(Dish::getCalories).reduce(Integer::max);复制代码07 总结这篇文章主要介绍了 Stream API 的相关使用,从文中所列举的例子可以看出:通过使用 Stream API 可以简化代码,同时还提高了代码可读性。所以,赶紧在项目里用起来吧!

标签:Stream,stream,Arrays,integerList,代码,List,Dish,优化
From: https://blog.51cto.com/u_15746412/5748336

相关文章

  • 使用 Stream API 高逼格 优化 Java 代码
    Java8的新特性主要是Lambda表达式和流,当流和Lambda表达式结合起来一起使用时,因为流申明式处理数据集合的特点,可以让代码变得简洁易读放大招,流如何简化代码如果有一个需求,需......
  • 详解MongoDB索引优化
    一、索引简介索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。1.1概念索引最常用的比喻就......
  • 对于查询代码的进一步优化
    本次没有相应模板,//index.jsp<%@pagecontentType="text/html;charset=UTF-8"pageEncoding="UTF-8"language="java"%><html><head><title>查询界面</title>......
  • 【图论——第七讲】Pirm算法求最小生成树问题及其堆优化
    文章目录​​一、前言​​​​二、Pirm算法求最小生成树​​​​三、Pirm算法堆优化​​​​最后​​一、前言最小生成树定义:一个有n个结点的连通图的生成树是原图的极小......
  • 第一行代码3:ContentProvider问题
    在providertest项目中查询databasetest项目的数据库出现问题Failedtofindproviderinfoforcom.example.databasetest.providerjava.lang.IllegalArgumentException:......
  • <三>从编译器角度理解C++代码的编译和链接原理
    代码点击查看代码**sum.cpp**intgdata=10;intsum(inta,intb){returna+b;}**main.cpp**externintgdata;intsum(int,int);intdata=20;intmain(......
  • 代码随想录 | 二叉树
    226.翻转二叉树给你一棵二叉树的根节点root,翻转这棵二叉树,并返回其根节点。输入:root=[4,2,7,1,3,6,9]输出:[4,7,2,9,6,3,1]ψ(`∇´)ψ我的思路还是用了层序......
  • Map.Entry详解及List的流Stream
    Map.Entry详解Map是java中的接口,Map.Entry是Map的一个内部接口。Map提供了一些常用方法,如keySet()、entrySet()等方法。keySet()方法返回值是Map中key值的集合;entrySet(......
  • 12、Java——对象和类案例代码详解
    ❤️ 目录​​⛳️案例一、写一个人的类​​​​⛳️案例二、写一个汽车类​​​​⛳️案例三、定义一个描述坐标点的类​​​​⛳️案例四、定义一个圆类型​​​​⛳️案例五、......
  • 【code基础】stream流简化数组的求最大值
    将集合或者数组转化为流,进行求最大值,排序,可以省去for循环,简化代码量Arrays.stream(res).max().getAsInt()可以得到res数组的最大值Arrays.stream(res).sorted().boxed(......