Collector的使用

一、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}

 

 

 

 

 

 

 

 

 

 

-----

 

转载于:https://www.cnblogs.com/tenWood/p/11530945.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值