一、Collector的引入
1)Collector的聚合作用前面已经使用过,将list.stream后的一系列操作之后再返回list。
2)Collector的引入,通过需求:将绿色的Apple放在一个list,黄色的Apple放在一个list
代码例子:
1 package com.cy.java8; 2 3 import java.util.*; 4 import java.util.stream.Collectors; 5 6 public class CollectorIntroduce { 7 8 public static void main(String[] args) { 9 List<Apple> list = Arrays.asList(new Apple("green", 150), 10 new Apple("yellow", 120), 11 new Apple("green", 170), 12 new Apple("green", 150), 13 new Apple("yellow", 120), 14 new Apple("green", 170) ); 15 16 //Collector的聚合作用 17 List<Apple> greenList = list.stream().filter(a -> a.getColor().equals("green")).collect(Collectors.toList()); 18 System.out.println(greenList); 19 20 Map<String, List<Apple>> result1 = groupByNormal(list); 21 System.out.println(result1); 22 23 Map<String, List<Apple>> result2 = groupByFunction(list); 24 System.out.println(result2); 25 26 //Collector的groupBy 27 Map<String, List<Apple>> result3 = groupByCollector(list); 28 System.out.println(result3); 29 } 30 31 32 33 /** 34 * 需求:将绿色的放在一个list,黄色的放在一个list 35 * 以前的写法 36 */ 37 private static Map<String, List<Apple>> groupByNormal(List<Apple> apples){ 38 Map<String, List<Apple>> map = new HashMap<>(); 39 40 for(Apple a : apples){ 41 List<Apple> list = map.get(a.getColor()); 42 if(list == null){ 43 list = new ArrayList<>(); 44 map.put(a.getColor(), list); 45 } 46 list.add(a); 47 } 48 49 return map; 50 } 51 52 /** 53 * 需求:将绿色的放在一个list,黄色的放在一个list 54 * 使用FunctionInterface的方法 55 * 虽然去掉了判断null的操作,但是也还是非常啰嗦,不够精简 56 */ 57 private static Map<String, List<Apple>> groupByFunction(List<Apple> apples){ 58 Map<String, List<Apple>> map = new HashMap<>(); 59 60 apples.stream().forEach(a -> { 61 List<Apple> colorList = Optional.ofNullable(map.get(a.getColor())).orElseGet(() -> { 62 List<Apple> list = new ArrayList<>(); 63 map.put(a.getColor(), list); 64 return list; 65 }); 66 colorList.add(a); 67 }); 68 69 return map; 70 } 71 72 /** 73 * 需求:将绿色的放在一个list,黄色的放在一个list 74 * 使用Collector 75 */ 76 private static Map<String, List<Apple>> groupByCollector(List<Apple> apples){ 77 return apples.stream().collect(Collectors.groupingBy(Apple::getColor)); 78 } 79 }
打印结果:
[Apple(color=green, weight=150), Apple(color=green, weight=170), Apple(color=green, weight=150), Apple(color=green, weight=170)] {green=[Apple(color=green, weight=150), Apple(color=green, weight=170), Apple(color=green, weight=150), Apple(color=green, weight=170)], yellow=[Apple(color=yellow, weight=120), Apple(color=yellow, weight=120)]} {green=[Apple(color=green, weight=150), Apple(color=green, weight=170), Apple(color=green, weight=150), Apple(color=green, weight=170)], yellow=[Apple(color=yellow, weight=120), Apple(color=yellow, weight=120)]} {green=[Apple(color=green, weight=150), Apple(color=green, weight=170), Apple(color=green, weight=150), Apple(color=green, weight=170)], yellow=[Apple(color=yellow, weight=120), Apple(color=yellow, weight=120)]}
二、
-----
原文:https://www.cnblogs.com/tenWood/p/11530945.html