jdk1.8 -- Collectors 的使用

Posted mrrightzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdk1.8 -- Collectors 的使用相关的知识,希望对你有一定的参考价值。

 

 

package com.collector;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.zpb.video_06.Dish;
import com.zpb.video_06.Dish.Type;

/**
 * @des        Collector API的使用
 *                 三大功能:聚合    分组     统计                          
 * @author  zhao
 * @date    2019年9月22日下午11:53:54
 * 
 */
public class CollectorsAPI {
    
    public static final List<Dish> menu =  Arrays.asList(
            new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), 
            new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("french fries", true, 530, Dish.Type.OTHER),
            new Dish("rice", true, 350, Dish.Type.OTHER),
            new Dish("season fruit", true, 120, Dish.Type.OTHER), 
            new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 300, Dish.Type.FISH), 
            new Dish("salmon", false, 450, Dish.Type.FISH));
    
    public static void main(String[] args) {
        //1.求平均值
        testAveragingDouble();
        testaveragingInt();
        testAveragingLong();
        testCollectingAndThen();
        
        //2.统计
        testCounting();
        testGroupByFunction();
        testGroupByFunctionAndCollectors();
        testGroupByFunctionAndAndCollectors();
        testSummarizingInt();
    }
    
    private static void testSummarizingInt() {
        IntSummaryStatistics intSummary = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
        Optional.ofNullable(intSummary).ifPresent(System.out::println);
    }
    
    
    private static void testGroupByFunctionAndAndCollectors() {
        System.out.println("...testGroupByFunctionAndCollectors...");
        Map<Type, Double> map = menu.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.averagingDouble(Dish::getCalories)));
        Optional.ofNullable(map.getClass()).ifPresent(System.out::println);        //hashmap 
        //我们得到的是hashMap, 下面把它改成treeMap
        TreeMap<Type, Double> map2 = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingDouble(Dish::getCalories)));
        Optional.ofNullable(map2.getClass()).ifPresent(System.out::println);
        
    }
    
    private static void testGroupByFunctionAndCollectors() {
        System.out.println("...testGroupByFunctionAndCollectors...");
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting())))
        .ifPresent(System.out::println);
        
        //每个分类下卡路里平均值
        Optional.ofNullable(
        menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingDouble(Dish::getCalories))))
        .ifPresent(System.out::println);
    }
    private static void testGroupByFunction() {
        System.out.println("...testGroupByFunction...");
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType)))
                .ifPresent(System.out::println);
    }
    
    private static void testCounting() {
        System.out.println("...testCounting...");
        Optional.ofNullable(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println);
    }
    private static void testAveragingDouble() {
        System.out.println("...testAveragingDouble...");
        Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories)))
        .ifPresent(System.out::println);
    }
    
    private static void testaveragingInt() {
        System.out.println("...testaveragingInt...");
        Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories)))
        .ifPresent(System.out::println);
    }
    
    private static void testAveragingLong() {
        System.out.println("...testAveragingLong...");
        Optional.ofNullable(menu.stream().collect(Collectors.averagingLong(Dish::getCalories)))
        .ifPresent(System.out::println);
    }
    private static void testCollectingAndThen() {
        /**
         * collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher)
         *   第1个参数是: Collector,也就是通过Collectors拿到的集合
         *   第2个参数是:Function,也就是传入2个参数,R RR,返回的是RR
         *  该方法最主要是要用好参数是怎么传入的
         */
        System.out.println("...testCollectingAndThen...");
        
        //1.获取到平均值,然后变成字符串输出
        Optional.ofNullable(menu.stream().
                collect(Collectors.collectingAndThen(Collectors.averagingLong(Dish::getCalories), a->"calories avg is "+a)))
                .ifPresent(System.out::println);
        
        //2.得到指定集合,不能被别人修改
        List<Dish> collect = menu.stream().filter(m->m.getType().equals(Type.MEAT))
            .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
        Optional.ofNullable(collect).orElseGet(ArrayList::new).forEach(System.out::println);
        
    }
    
}

 

package com.collector;

import java.awt.Menu;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.collector.CollectorsAPI;
import com.zpb.video_06.Dish;
import com.zpb.video_06.Dish.Type;
/**
 * @des                                  
 * @author  zhao
 * @date    2019年9月24日上午12:13:00
 * 
 */
public class CollectorsAPI2 {
    
    static List<Dish> menu = CollectorsAPI.menu;
    
    public static void main(String[] args) {
        
        testGroupingByConcurrent();
        testGroupingByConcurrentAndCollectors();
        testGroupingByConcurrentAndSkipAndCollectors();
        testJoining();
        testJoiningAndPrefixAndSuffix();
        testMapping();
    }
    
    public static void testMapping() {
        System.out.println(">>>>>>>>>>>>>>> testMapping  >>>>>>>>>>>>>>>");
        /**
         *  mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {
         *  第1个参数得到的结果作为第2个参数操作的源数据
         */
        Optional.ofNullable(menu.stream().collect(Collectors.mapping(Dish::getName, Collectors.joining(","))))
                .ifPresent(System.out::println);
                
    }
    
    //连接操作
    public static void testJoining() {
        System.out.println(">>>>>>>>>>>>>>> testJoining()  >>>>>>>>>>>>>>>");
        Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining("#")))
                .ifPresent(System.out::println);
    }
    public static void testJoiningAndPrefixAndSuffix() {
        System.out.println(">>>>>>>>>>>>>>> testJoiningAndPrefixAndSuffix()  >>>>>>>>>>>>>>>");
        Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(",","Name[","]")))
        .ifPresent(System.out::println);
    }
    
    public static void testGroupingByConcurrentAndSkipAndCollectors() {
        System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrentAndSkipAndCollectors()  >>>>>>>>>>>>>>>");
        ConcurrentSkipListMap<Type, Double> skipListMap = 
            menu.stream().collect(Collectors.groupingBy(Dish::getType, ConcurrentSkipListMap::new,Collectors.averagingDouble(Dish::getCalories)));
    
        Optional.ofNullable(skipListMap.getClass()).ifPresent(System.out::println);
        Optional.ofNullable(skipListMap).ifPresent(System.out::println);
                
    }
    
    public static void testGroupingByConcurrentAndCollectors() {
        System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrentAndCollectors >>>>>>>>>>>>>>>");
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingDouble(Dish::getCalories))))
                .ifPresent(System.out::println);
    }
    //1.按类型分类,返回类型是:CurrentMap
    public static void testGroupingByConcurrent() {
        System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrent >>>>>>>>>>>>>>>");
        Optional.ofNullable(menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType)))
                .ifPresent(System.out::println);
    }
    
}

 

以上是关于jdk1.8 -- Collectors 的使用的主要内容,如果未能解决你的问题,请参考以下文章

JDK1.8新特性:Collectors收集器类

JDK1.8新特性Stream和Collectors19个常用示例总结

jdk1.8

内存模型

内存模型

jdk1.8中list按对象的多个属性去重,按对象的某个属性分组