巧用Stream优化老代码,太清爽了!
阅读本文大概需要 10 分钟。
来自:https://sourl.cn/DNU3FV
放大招,流如何简化代码
如果有一个需求,需要对数据库查询到的菜肴进行一个处理:
筛选出卡路里小于400的菜肴
对筛选出的菜肴进行一个排序
获取排序后菜肴的名字
public class Dish { private String name; private boolean vegetarian; private int calories; private Type type; // getter and setter}private ListbeforeJava7(List {dishList )ListlowCaloricDishes = new ArrayList<>(); //1.筛选出卡路里小于400的菜肴for (Dish dish : dishList) {if (dish.getCalories() < 400) {lowCaloricDishes.add(dish);}}//2.对筛选出的菜肴进行排序Collections.sort(lowCaloricDishes, new Comparator() { @Overridepublic 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 ListafterJava8(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 MapList > afterJdk8(List dishList) { return dishList.stream().collect(groupingBy(Dish::getType));}

什么是流
流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算。
如何生成流
生成流的方式主要有五种。
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);Stream<Integer> stream = integerList.stream();
int[] intArr = new int[]{1, 2, 3, 4, 5};IntStream stream = Arrays.stream(intArr);
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())
Streamstream = Stream.iterate(0, n -> n + 2).limit(5);
Streamstream = Stream.generate(Math::random).limit(5);
流的操作类型
流的操作类型主要分为两种。
流的使用
流的使用将分为终端操作和中间操作进行介绍。
中间操作
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream<Integer> stream = integerList.stream().filter(i -> i > 3);
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream<Integer> stream = integerList.stream().distinct();
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream<Integer> stream = integerList.stream().limit(3);
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);Stream<Integer> stream = integerList.stream().skip(2);
List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");Streamstream = stringList.stream().map(String::length);
ListwordList = Arrays.asList("Hello", "World"); ListstrList = wordList.stream() .map(w -> w.split(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
ListintegerList = Arrays.asList(1, 2, 3, 4, 5); if (integerList.stream().allMatch(i -> i > 3)) {System.out.println("值都大于3");}
ListintegerList = 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;}}
ListintegerList = Arrays.asList(1, 2, 3, 4, 5); if (integerList.stream().noneMatch(i -> i > 3)) {System.out.println("值都小于3");}
终端操作
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);Long result = integerList.stream().count();
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);Long result = integerList.stream().collect(counting());
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);Optional<Integer> result = integerList.stream().filter(i -> i > 3).findFirst();
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);Optional<Integer> result = integerList.stream().filter(i -> i > 3).findAny();
int sum = 0;for (int i : integerList) {sum += i;}
int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
int sum = integerList.stream().reduce(0, Integer::sum);
Optional<Integer> min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);Optional<Integer> 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();
Optionalmin = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo)); Optionalmax = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
Optional<Integer> min = menu.stream().map(Dish::getCalories).reduce(Integer::min);Optional<Integer> max = menu.stream().map(Dish::getCalories).reduce(Integer::max);
int sum = menu.stream().collect(summingInt(Dish::getCalories));
int sum = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum);
int sum = menu.stream().mapToInt(Dish::getCalories).sum();
double average = menu.stream().collect(averagingInt(Dish::getCalories));
IntSummaryStatistics intSummaryStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));double average = intSummaryStatistics.getAverage(); //获取平均值int min = intSummaryStatistics.getMin(); //获取最小值int max = intSummaryStatistics.getMax(); //获取最大值long sum = intSummaryStatistics.getSum(); //获取总和
ListintegerList = Arrays.asList(1, 2, 3, 4, 5); integerList.stream().forEach(System.out::println);
for (int i : integerList) {System.out.println(i);}
List<String> strings = menu.stream().map(Dish::getName).collect(toList());Set<String> sets = menu.stream().map(Dish::getName).collect(toSet());
List<String> stringList = new ArrayList<>();Set<String> stringSet = new HashSet<>();for (Dish dish : menu) {stringList.add(dish.getName());stringSet.add(dish.getName());}
String result = menu.stream().map(Dish::getName).collect(Collectors.joining(", "));
Map>> result = dishList.stream().collect(groupingBy(Dish::getType));
Map> result = menu.stream().collect(groupingBy(Dish::getType, groupingBy(dish -> {if (dish.getCalories() <= 400) return CaloricLevel.DIET;else if (dish.getCalories() <= 700) return CaloricLevel.NORMAL;else return CaloricLevel.FAT;})));
Map<Boolean, List> result = menu.stream().collect(partitioningBy(Dish :: isVegetarian))
Map<Boolean, List> result = menu.stream().collect(groupingBy(Dish :: isVegetarian))
ListintegerList = Arrays.asList(1, 2, 3, 4, 5); Map<Boolean, List> result = integerList.stream().collect(partitioningBy(i -> i < 3));
总 结
通过使用Stream API可以简化代码,同时提高了代码可读性,赶紧在项目里用起来。讲道理在没学Stream API之前,谁要是给我在应用里写很多Lambda,Stream API,飞起就想给他一脚。


推荐阅读:
Typora 收费,这款开源 Markdown 神器值得一试
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅 
评论

