巧用Stream優(yōu)化老代碼,太清爽了!
閱讀本文大概需要 10?分鐘。
來自:https://sourl.cn/DNU3FV
放大招,流如何簡化代碼
如果有一個需求,需要對數(shù)據(jù)庫查詢到的菜肴進行一個處理:
篩選出卡路里小于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)) //根據(jù)卡路里進行排序.map(Dish::getName) //提取菜肴名稱.collect(Collectors.toList()); //轉(zhuǎn)換為List}

對數(shù)據(jù)庫查詢到的菜肴根據(jù)菜肴種類進行分類,返回一個Map >的結(jié)果
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));}

什么是流
流是從支持數(shù)據(jù)處理操作的源生成的元素序列,源可以是數(shù)組、文件、集合、函數(shù)。流不是集合元素,它不是數(shù)據(jù)結(jié)構并不保存數(shù)據(jù),它的主要目的在于計算。
如何生成流
生成流的方式主要有五種。
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));
總 結(jié)
通過使用Stream API可以簡化代碼,同時提高了代碼可讀性,趕緊在項目里用起來。講道理在沒學Stream API之前,誰要是給我在應用里寫很多Lambda,Stream API,飛起就想給他一腳。


推薦閱讀:
Typora 收費,這款開源 Markdown 神器值得一試
內(nèi)容包含Java基礎、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務、Zookeeper、數(shù)據(jù)結(jié)構、限流熔斷降級......等技術棧!
?戳閱讀原文領取!? ? ? ? ? ? ? ??? ??? ? ? ? ? ? ? ? ? ?朕已閱?
評論
圖片
表情

