一、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)]}
二、Collectors的API介绍和使用
averagingDouble;
averagingInt;
averagingLong;
collectingAndThen;
counting;
groupingBy;
summarizingInt;
代码例子:
1 package com.cy.java8; 2 3 import java.util.*; 4 import java.util.stream.Collectors; 5 6 public class CollectorsAction { 7 private final static List<Dish> menu = Arrays.asList( 8 new Dish("pork", false, 800, Dish.Type.MEAT), 9 new Dish("beef", false, 700, Dish.Type.MEAT), 10 new Dish("chicken", false, 400, Dish.Type.MEAT), 11 new Dish("french fries", true, 530, Dish.Type.OTHER), 12 new Dish("rice", true, 350, Dish.Type.OTHER), 13 new Dish("season fruit", true, 120, Dish.Type.OTHER), 14 new Dish("pizza", true, 550, Dish.Type.OTHER), 15 new Dish("prawns", false, 300, Dish.Type.FISH), 16 new Dish("salmon", false, 450, Dish.Type.FISH)); 17 18 19 public static void main(String[] args) { 20 testAveragingDouble(); 21 testAveragingInt(); 22 testCollectingAndThen(); 23 testCounting(); 24 testGroupingByFunction(); 25 testGroupingByFunctionAndCollector(); 26 testGroupingByFunctionAndSupplierAndCollector(); 27 testSummarizingInt(); 28 } 29 30 /** 31 * 计算menu中食物们卡路里的平均数 32 */ 33 private static void testAveragingDouble(){ 34 System.out.println("testAveragingDouble"); 35 Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories))) 36 .ifPresent(System.out::println); 37 } 38 39 /** 40 * testAveragingInt和testAveragingLong的返回值类型也是Double,和上面类似 41 */ 42 private static void testAveragingInt(){ 43 System.out.println("testAveragingInt"); 44 Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories))) 45 .ifPresent(System.out::println); 46 } 47 48 private static void testCollectingAndThen(){ 49 System.out.println("testCollectingAndThen"); 50 Optional.ofNullable(menu.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), v-> "The Average Calories is " + v))) 51 .ifPresent(System.out::println); 52 53 } 54 55 /** 56 * 计算list<Dish>的count 57 */ 58 private static void testCounting(){ 59 System.out.println("testCounting"); 60 Long count = menu.stream().collect(Collectors.counting()); 61 System.out.println(count); 62 } 63 64 /** 65 * 将menu按照type类型分组 66 */ 67 private static void testGroupingByFunction(){ 68 System.out.println("testGroupingByFunction"); 69 Map<Dish.Type, List<Dish>> map = menu.stream().collect(Collectors.groupingBy(dish -> dish.getType())); 70 System.out.println(map); 71 } 72 73 /** 74 * 将menu按照type分组,并计算每个组元素数量 75 */ 76 private static void testGroupingByFunctionAndCollector(){ 77 System.out.println("testGroupingByFunctionAndCollector"); 78 Map<Dish.Type, Long> map1 = menu.stream().collect(Collectors.groupingBy(dish -> dish.getType(), Collectors.counting())); 79 System.out.println(map1); 80 81 //每个类型卡路里的平均值 82 Map<Dish.Type, Double> map2 = menu.stream().collect(Collectors.groupingBy(dish -> dish.getType(), Collectors.averagingInt(Dish::getCalories))); 83 System.out.println(map2); 84 } 85 86 /** 87 * Supplier mapFactory,第2个参数,可以指定传入什么类型的map 88 */ 89 private static void testGroupingByFunctionAndSupplierAndCollector(){ 90 System.out.println("testGroupingByFunctionAndSupplierAndCollector"); 91 Map<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingInt(Dish::getCalories))); 92 System.out.println(map.getClass()); 93 System.out.println(map); 94 } 95 96 /** 97 * 将菜单menu按照卡路里进行汇总 98 */ 99 private static void testSummarizingInt(){ 100 System.out.println("testSummarizingInt"); 101 IntSummaryStatistics result = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories)); 102 System.out.println(result); 103 } 104 }
打印结果:
testAveragingDouble 466.6666666666667 testAveragingInt 466.6666666666667 testCollectingAndThen The Average Calories is 466.6666666666667 testCounting 9 testGroupingByFunction {MEAT=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}], OTHER=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}], FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}]} testGroupingByFunctionAndCollector {MEAT=3, OTHER=4, FISH=2} {MEAT=633.3333333333334, OTHER=387.5, FISH=375.0} testGroupingByFunctionAndSupplierAndCollector class java.util.TreeMap {MEAT=633.3333333333334, FISH=375.0, OTHER=387.5} testSummarizingInt IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
三、Collectors的API介绍和使用2
GroupingByConcurrent;
joining;
mapping;
maxBy
代码举例如下:
1 package com.cy.java8; 2 3 import java.util.Comparator; 4 import java.util.List; 5 import java.util.Optional; 6 import java.util.concurrent.ConcurrentMap; 7 import java.util.concurrent.ConcurrentSkipListMap; 8 import java.util.stream.Collectors; 9 import static com.cy.java8.CollectorsAction.menu; 10 11 public class CollectorsAction2 { 12 13 public static void main(String[] args) { 14 testGroupingByConcurrentWithFunction(); 15 testGroupingByConcurrentWithFunctionAndCollector(); 16 testGroupingByConcurrentWithFunctionAndSupplierAndCollector(); 17 testJoining(); 18 testMapping(); 19 testMaxBy(); 20 } 21 22 /** 23 * 按食物类型分类 24 */ 25 private static void testGroupingByConcurrentWithFunction() { 26 System.out.println("testGroupingByConcurrentWithFunction"); 27 ConcurrentMap<Dish.Type, List<Dish>> map = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType)); 28 System.out.println(map.getClass()); 29 System.out.println(map); 30 } 31 32 /** 33 * 每类食物类型下面 卡路里平均值 34 */ 35 private static void testGroupingByConcurrentWithFunctionAndCollector() { 36 System.out.println("testGroupingByConcurrentWithFunctionAndCollector"); 37 ConcurrentMap<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType, Collectors.averagingInt(Dish::getCalories))); 38 System.out.println(map); 39 } 40 41 private static void testGroupingByConcurrentWithFunctionAndSupplierAndCollector() { 42 System.out.println("testGroupingByConcurrentWithFunctionAndCollector"); 43 ConcurrentMap<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType, ConcurrentSkipListMap::new, Collectors.averagingInt(Dish::getCalories))); 44 System.out.println(map.getClass()); 45 System.out.println(map); 46 } 47 48 /** 49 * joining: 对stream里面的一些值进行连接 50 * 对食物的名字进行连接 51 */ 52 private static void testJoining() { 53 System.out.println("testJoining"); 54 String s = menu.stream().map(Dish::getName).collect(Collectors.joining(",", "Names[", "]")); 55 System.out.println(s); 56 } 57 58 /** 59 * 用一个mapping function在汇聚之前,将接受Dish的集合适用于接受DishName的集合 60 */ 61 private static void testMapping() { 62 System.out.println("testMapping"); 63 String s = menu.stream().collect(Collectors.mapping(d -> d.getName(), Collectors.joining(",", "Names[", "]"))); 64 System.out.println(s); 65 } 66 67 /** 68 * 找出热量最大的食物 69 */ 70 private static void testMaxBy(){ 71 System.out.println("testMaxBy"); 72 Optional<Dish> maxCaloriesOptional = menu.stream().collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories))); 73 maxCaloriesOptional.ifPresent(System.out::println); 74 } 75 76 77 }
打印结果:
testGroupingByConcurrentWithFunction class java.util.concurrent.ConcurrentHashMap {FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}], MEAT=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}], OTHER=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}]} testGroupingByConcurrentWithFunctionAndCollector {FISH=375.0, MEAT=633.3333333333334, OTHER=387.5} testGroupingByConcurrentWithFunctionAndCollector class java.util.concurrent.ConcurrentSkipListMap {MEAT=633.3333333333334, FISH=375.0, OTHER=387.5} testJoining Names[pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon] testMapping Names[pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon] testMaxBy Dish{name='pork', vegetarian=false, calories=800, type=MEAT}
四、Collectors的API介绍和使用3
partitioningBy
reduce
summarizingDouble
summarizingLong
summarizingInt
代码举例如下:
1 package com.cy.java8; 2 3 import java.util.*; 4 import java.util.function.BinaryOperator; 5 import java.util.stream.Collectors; 6 7 import static com.cy.java8.CollectorsAction.menu; 8 9 public class CollectorsAction3 { 10 11 public static void main(String[] args) { 12 testPartitioningByWithPredicate(); 13 testPartitioningByWithPredicateAndCollector(); 14 testReducingBinaryOperator(); 15 testReducingBinaryOperatorAndIdentity(); 16 testReducingBinaryOperatorAndIdentityAndFunction(); 17 testSummarizingDouble(); 18 testSummarizingLong(); 19 testSummarizingInt(); 20 } 21 22 /** 23 * 利用partitioningBy把menu中素食类和非素食类的分开 24 */ 25 private static void testPartitioningByWithPredicate() { 26 System.out.println("testPartitioningByPredicate"); 27 Map<Boolean, List<Dish>> map = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian)); 28 System.out.println(map); 29 } 30 31 /** 32 * 把素食类和非素食类分开,计算平均卡路里 33 */ 34 private static void testPartitioningByWithPredicateAndCollector() { 35 System.out.println("testPartitioningByWithPredicateAndCollector"); 36 Map<Boolean, Double> map = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian, Collectors.averagingInt(Dish::getCalories))); 37 System.out.println(map); 38 System.out.println(map.get(true)); 39 } 40 41 /** 42 * 找出menu中热量最大的dish 43 */ 44 private static void testReducingBinaryOperator() { 45 System.out.println("testReducingBinaryOperator"); 46 //以前这么写 47 Optional<Dish> optional = menu.stream().reduce((dish1, dish2) -> dish1.getCalories() > dish2.getCalories() ? dish1 : dish2); 48 optional.ifPresent(System.out::println); 49 50 //Collectors.reducing 51 Optional<Dish> optional2 = menu.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Dish::getCalories)))); 52 optional2.ifPresent(System.out::println); 53 54 Optional<Dish> optional3 = menu.stream().collect(Collectors.reducing((dish1, dish2) -> dish1.getCalories() > dish2.getCalories() ? dish1 : dish2)); 55 optional3.ifPresent(System.out::println); 56 } 57 58 /** 59 * 计算所有卡路里和 60 */ 61 private static void testReducingBinaryOperatorAndIdentity() { 62 System.out.println("testReducingBinaryOperatorAndIdentity"); 63 //以前这么写 64 Integer totalCalories1 = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum); 65 System.out.println(totalCalories1); 66 67 //Collectors.reducing 68 Integer totalCalories2 = menu.stream().map(Dish::getCalories).collect(Collectors.reducing(0, Integer::sum)); 69 System.out.println(totalCalories2); 70 } 71 72 private static void testReducingBinaryOperatorAndIdentityAndFunction() { 73 System.out.println("testReducingBinaryOperatorAndIdentityAndFunction"); 74 Integer result = menu.stream().collect(Collectors.reducing(0, Dish::getCalories, (d1, d2) -> d1 + d2)); 75 System.out.println(result); 76 } 77 78 private static void testSummarizingDouble(){ 79 System.out.println("testSummarizingDouble"); 80 DoubleSummaryStatistics result = menu.stream().collect(Collectors.summarizingDouble(Dish::getCalories)); 81 System.out.println(result); 82 } 83 84 private static void testSummarizingLong(){ 85 System.out.println("testSummarizingLong"); 86 LongSummaryStatistics result = menu.stream().collect(Collectors.summarizingLong(Dish::getCalories)); 87 System.out.println(result); 88 } 89 90 private static void testSummarizingInt(){ 91 System.out.println("testSummarizingInt"); 92 IntSummaryStatistics result = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories)); 93 System.out.println(result); 94 } 95 }
打印结果:
testPartitioningByPredicate {false=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}, Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}], true=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}]} testPartitioningByWithPredicateAndCollector {false=530.0, true=387.5} 387.5 testReducingBinaryOperator Dish{name='pork', vegetarian=false, calories=800, type=MEAT} Dish{name='pork', vegetarian=false, calories=800, type=MEAT} Dish{name='pork', vegetarian=false, calories=800, type=MEAT} testReducingBinaryOperatorAndIdentity 4200 4200 testReducingBinaryOperatorAndIdentityAndFunction 4200 testSummarizingDouble DoubleSummaryStatistics{count=9, sum=4200.000000, min=120.000000, average=466.666667, max=800.000000} testSummarizingLong LongSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800} testSummarizingInt IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
五、Collectors的API介绍和使用4
summingDouble
summingLong
summingInt
toCollection
toConcurrentMap
toMap
toList
toSet
代码举例如下:
1 package com.cy.java8; 2 3 import java.util.LinkedList; 4 import java.util.List; 5 import java.util.Set; 6 import java.util.concurrent.ConcurrentMap; 7 import java.util.concurrent.ConcurrentSkipListMap; 8 import java.util.stream.Collectors; 9 import static com.cy.java8.CollectorsAction.menu; 10 11 public class CollectorsAction4 { 12 13 public static void main(String[] args) { 14 testSummingDouble(); 15 testToCollection(); 16 testToConcurrentMap(); 17 testToConcurrentMapAndBinaryOperator(); 18 testToConcurrentMapAndBinaryOperatorAndSupplier(); 19 testToList(); 20 testToSet(); 21 } 22 23 /** 24 * 计算卡路里总和 25 */ 26 private static void testSummingDouble(){ 27 System.out.println("testSummingDouble--------------"); 28 //以前的写法 29 double sum = menu.stream().map(Dish::getCalories).mapToDouble(Integer::doubleValue).sum(); 30 System.out.println(sum); 31 32 //Collectors.summingDouble 33 Double sum2 = menu.stream().collect(Collectors.summingDouble(Dish::getCalories)); 34 System.out.println(sum2); 35 } 36 37 private static void testToCollection(){ 38 System.out.println("testToCollection--------------"); 39 LinkedList<Dish> list = menu.stream().filter(dish -> dish.getCalories() > 600).collect(Collectors.toCollection(LinkedList::new)); 40 System.out.println(list); 41 } 42 43 private static void testToConcurrentMap(){ 44 System.out.println("testToConcurrentMap--------------"); 45 ConcurrentMap<String, Integer> map = menu.stream().filter(dish -> dish.getCalories() > 600).collect(Collectors.toConcurrentMap(d -> d.getName(), d -> d.getCalories())); 46 System.out.println(map); 47 } 48 49 /** 50 * Type : total 51 * 将menu转化为,key是type,value是这个type下有多少个,这样的map 52 */ 53 private static void testToConcurrentMapAndBinaryOperator(){ 54 System.out.println("testToConcurrentMapAndBinaryOperator--------------"); 55 ConcurrentMap<Dish.Type, Integer> map = menu.stream().collect(Collectors.toConcurrentMap(Dish::getType, d -> 1, (v1, v2) -> v1 + v2)); 56 System.out.println(map.getClass()); 57 System.out.println(map); 58 } 59 60 private static void testToConcurrentMapAndBinaryOperatorAndSupplier(){ 61 System.out.println("testToConcurrentMapAndBinaryOperatorAndSupplier--------------"); 62 ConcurrentSkipListMap<Dish.Type, Integer> map = menu.stream().collect(Collectors.toConcurrentMap(Dish::getType, d -> 1, (v1, v2) -> v1 + v2, ConcurrentSkipListMap::new)); 63 System.out.println(map.getClass()); 64 System.out.println(map); 65 } 66 67 private static void testToList() { 68 System.out.println("testToList--------------"); 69 List<Dish> list = menu.stream().filter(Dish::isVegetarian).collect(Collectors.toList()); 70 System.out.println(list.getClass()); 71 System.out.println(list); 72 } 73 74 /** 75 * 返回值类型为集合HashSet,里面的值不能重复,根据hashCode和equals做的判断 76 */ 77 private static void testToSet() { 78 System.out.println("testToSet--------------"); 79 Set<Dish> set = menu.stream().filter(Dish::isVegetarian).collect(Collectors.toSet()); 80 System.out.println(set.getClass()); 81 System.out.println(set); 82 } 83 84 /** 85 * toMap : 略 86 * toMap 和上面的 toConcurrentMap用法是一样的,只不过返回的是HashMap 87 */ 88 }
打印结果:
testSummingDouble-------------- 4200.0 4200.0 testToCollection-------------- [Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}] testToConcurrentMap-------------- {beef=700, pork=800} testToConcurrentMapAndBinaryOperator-------------- class java.util.concurrent.ConcurrentHashMap {OTHER=4, FISH=2, MEAT=3} testToConcurrentMapAndBinaryOperatorAndSupplier-------------- class java.util.concurrent.ConcurrentSkipListMap {MEAT=3, FISH=2, OTHER=4} testToList-------------- class java.util.ArrayList [Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}] testToSet-------------- class java.util.HashSet [Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}]
-----