java8_流操作demo

java8_流操作demo
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码

流操作demo

package com.example.mapper;

import org.junit.Before;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.stream.Collectors.*;

/**
 * @desc stream
 * @author LT
 */
public class StreamTest {

    //-------------------------------------创建流-----------------------------------------------------------------------

    /**
     * 通过数组创建流
     */
    @Test
    public void testArrayStream(){
        // 基本类型
        int[] arr = new int[]{1,2,34,55};
        IntStream intStream = Arrays.stream(arr);

        // 引用类型
        Student[] studentArr = new Student[]{new Student("张三",23),new Student("李四",25)};
        Stream<Student> studentStream = Arrays.stream(studentArr);

        // 方式2
        Stream<Integer> stream1 = Stream.of(1,2,34,65);
        Stream<int[]> stream2 = Stream.of(arr,arr);
        stream2.forEach(System.out::println);
    }

    /**
     * 通过集合创建流
     */
    @Test
    public void testCollectionStream(){
        List<String> strs = Arrays.asList("1112","dfs","2342","232");

        // 创建普通流
        Stream<String> stringStream = strs.stream();

        // 创建并行流
        Stream<String> stream = strs.parallelStream();

    }

    /**
     * 创建空的流
     */
    @Test
    public void testEmptyStream(){
        //创建一个空的stream
        Stream<Integer> stream  = Stream.empty();
    }

    /**
     * 创建无限流
     */
    @Test
    public void testUnlimitStream(){
        //创建无限流,通过limit提取指定大小
        Stream.generate(()->"number"+new Random().nextInt()).limit(100).forEach(System.out::println);
        Stream.generate(()->new Student("name",10)).limit(20).forEach(System.out::println);
        // 创建无限流集合并存放到集合中
        Stream<Integer> stream = Stream.generate(()-> new Random().nextInt()).limit(100);
        List<Integer> integerList = stream.collect(Collectors.toList());
        integerList.forEach(System.out::println);
    }

    /**
     * 产生规律的数据
     */
    @Test
    public void testUnlimitStream1(){
        Stream.iterate(1,x->x*2).limit(12).forEach(System.out::println);
    }


    /**
     * map把一种类型的流转换为另外一种类型的流
     * 将String数组中字母转换为小写
     */
    @Test
    public void testMap() {
        String[] arr = new String[]{"asdf", "Yrs", "no", "NO"};
        Arrays.stream(arr).map(x -> x.toLowerCase()).forEach(System.out::println);
    }

    /**
     * filter:过滤流,过滤流中的元素
     */
    @Test
    public void testFilter() {
        Integer[] arr = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        Arrays.stream(arr).filter(x -> x > 3 && x < 8).forEach(System.out::println);
    }

    /**
     * flapMap:拆解流
     */
    @Test
    public void testFlapMap1() {
        String[] arr1 = {"a", "b", "c", "d"};
        String[] arr2 = {"e", "f", "c", "d"};
        String[] arr3 = {"h", "j", "c", "d"};
        Stream.of(arr1, arr2, arr3).flatMap(Arrays::stream).forEach(System.out::println);
    }


    String[] arr1 = {"abc","a","bc","abcd"};
    /**
     * Comparator.comparing是一个键提取的功能
     */
    @Test
    public void testSorted1_(){
        /**
         * 按照字符长度排序
         */
        Arrays.stream(arr1).sorted((x,y)->{
            if (x.length()>y.length())
                return 1;
            else if (x.length()<y.length())
                return -1;
            else
                return 0;
        }).forEach(System.out::println);
        Arrays.stream(arr1).sorted(Comparator.comparing(String::length)).forEach(System.out::println);
    }

    /**
     * 倒序
     * reversed(),java8泛型推导的问题,所以如果comparing里面是非方法引用的lambda表达式就没办法直接使用reversed()
     * Comparator.reverseOrder():也是用于翻转顺序,用于比较对象(Stream里面的类型必须是可比较的)
     * Comparator. naturalOrder():返回一个自然排序比较器,用于比较对象(Stream里面的类型必须是可比较的)
     */
    @Test
    public void testSorted2_(){
        Arrays.stream(arr1).sorted(Comparator.comparing(String::length).reversed()).forEach(System.out::println);
        Arrays.stream(arr1).sorted(Comparator.reverseOrder()).forEach(System.out::println);
        Arrays.stream(arr1).sorted(Comparator.naturalOrder()).forEach(System.out::println);
    }

    /**
     * thenComparing
     * 先按照首字母排序
     * 之后按照String的长度排序
     */
    @Test
    public void testSorted3_(){
        Arrays.stream(arr1).sorted(Comparator.comparing(this::com1).thenComparing(String::length)).forEach(System.out::println);
    }
    public char com1(String x){
        return x.charAt(0);
    }


    //----------------------------------------------------------提取流和组合流--------------------------------------------------------------------------

    String[] arr11 = new String[]{"a","b","c","d"};
    String[] arr22 = new String[]{"d","e","f","g"};
    /**
     * limit,限制从流中获得前n个数据
     */
    @Test
    public void testLimit(){
        Stream.iterate(1,x->x+2).limit(10).forEach(System.out::println);
    }

    /**
     * skip,跳过前n个数据
     */
    @Test
    public void testSkip(){
        Stream.iterate(1,x->x+2).skip(1).limit(5).forEach(System.out::println);
    }

    /**
     * 可以把两个stream合并成一个stream(合并的stream类型必须相同)
     * 只能两两合并
     */
    @Test
    public void testConcat(){
        Stream<String> stream1 = Stream.of(arr11);
        Stream<String> stream2 = Stream.of(arr22);
        Stream.concat(stream1,stream2).distinct().forEach(System.out::println);
    }


//---------------------------------------------------------聚合操作--------------------------------------------------------------------------

   String[] arr33 = new String[]{"b","ab","abc","abcd","abcde"};

    /**
     * max、min
     * 最大最小值
     */
    @Test
    public void testMaxAndMin(){
        Stream.of(arr33).max(Comparator.comparing(String::length)).ifPresent(System.out::println);
        Stream.of(arr33).min(Comparator.comparing(String::length)).ifPresent(System.out::println);
    }

    /**
     * count
     * 计算数量
     */
    @Test
    public void testCount(){
        long count = Stream.of(arr33).count();
        System.out.println(count);
    }

    /**
     * findFirst
     * 查找第一个
     */
    @Test
    public void testFindFirst(){
        String str =  Stream.of(arr33).parallel().filter(x->x.length()>3).findFirst().orElse("noghing");
        System.out.println(str);
    }

    /**
     * findAny
     * 找到所有匹配的元素
     * 对并行流十分有效
     * 只要在任何片段发现了第一个匹配元素就会结束整个运算
     */
    @Test
    public void testFindAny(){
        Optional<String> optional = Stream.of(arr33).parallel().filter(x->x.length()>3).findAny();
        optional.ifPresent(System.out::println);
    }

    /**
     * anyMatch
     * 是否含有匹配元素
     */
    @Test
    public void testAnyMatch(){
        Boolean aBoolean = Stream.of(arr33).anyMatch(x->x.startsWith("a"));
        System.out.println(aBoolean);
    }


    @Test
    public void testStream1() {
        Optional<Integer> optional = Stream.of(1,2,3).filter(x->x>1).reduce((x,y)->x+y);
        System.out.println(optional.get());
    }

//    ------------------------------------------------ Optional类型-----------------------------------------------------------

    @Test
    public void testOptional2() {
        Integer[] arr = new Integer[]{4,5,6,7,8,9};
        Integer result = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElse(-1);
        System.out.println(result);
        Integer result1 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseGet(()->-1);
        System.out.println(result1);
        Integer result2 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseThrow(RuntimeException::new);
        System.out.println(result2);
    }

//    ------------------------------------------收集结果----------------------------------------------------------------------------
    Student[] students;
    @Before
    public void init(){
        students = new Student[100];
        for (int i=0;i<30;i++){
            Student student = new Student("user",i);
            students[i] = student;
        }
        for (int i=30;i<60;i++){
            Student student = new Student("user"+i,i);
            students[i] = student;
        }
        for (int i=60;i<100;i++){
            Student student = new Student("user"+i,i);
            students[i] = student;
        }

    }
    @Test
    public void testCollect1(){
        /**
         * 生成List
         */
        List<Student> list = Arrays.stream(students).collect(Collectors.toList());
        list.forEach((x)-> System.out.println(x));
        /**
         * 生成Set
         */
        Set<Student> set = Arrays.stream(students).collect(Collectors.toSet());
        set.forEach((x)-> System.out.println(x));
        /**
         * 如果包含相同的key,则需要提供第三个参数,否则报错
         */
        Map<String,Integer> map = Arrays.stream(students).collect(Collectors.toMap(Student::getName,Student::getScore,(s,a)->s+a));
        map.forEach((x,y)-> System.out.println(x+"->"+y));
    }

    /**
     * 生成数组
     */
    @Test
    public void testCollect2(){
        Student[] s = Arrays.stream(students).toArray(Student[]::new);
        for (int i=0;i<s.length;i++)
            System.out.println(s[i]);
    }

    /**
     * 指定生成的类型
     */
    @Test
    public void testCollect3(){
        HashSet<Student> s = Arrays.stream(students).collect(toCollection(HashSet::new));
        s.forEach(System.out::println);
    }

    /**
     * 统计
     */
    @Test
    public void testCollect4(){
        IntSummaryStatistics summaryStatistics = Arrays.stream(students).collect(Collectors.summarizingInt(Student::getScore));
        System.out.println("getAverage->"+summaryStatistics.getAverage());
        System.out.println("getMax->"+summaryStatistics.getMax());
        System.out.println("getMin->"+summaryStatistics.getMin());
        System.out.println("getCount->"+summaryStatistics.getCount());
        System.out.println("getSum->"+summaryStatistics.getSum());
    }

//    ---------------------------------------------------------------分组和分片----------------------------------------------------------
    /** * 按照名称分组 * */
    @Test
    public void testGroupBy1(){
        Map<String,List<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName));
        map.forEach((x,y)-> System.out.println(x+"->"+y));
    }

    /**
     * 如果只有两类,使用partitioningBy会比groupingBy更有效率,按照分数是否大于50分组
     */
    @Test
    public void testPartitioningBy(){
        Map<Boolean,List<Student>> map = Arrays.stream(students).collect(Collectors.partitioningBy(x->x.getScore()>50));
        map.forEach((x,y)-> System.out.println(x+"->"+y));
    }

    /**
     * downstream指定类型
     */
    @Test
    public void testGroupBy2(){
        Map<String,Set<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName,Collectors.toSet()));
        map.forEach((x,y)-> System.out.println(x+"->"+y));
    }

    /**
     * downstream 聚合操作
     */
    @Test
    public void testGroupBy3(){
        /**
         * counting
         */
        Map<String,Long> map1 = Arrays.stream(students).collect(groupingBy(Student::getName,Collectors.counting()));
        map1.forEach((x,y)-> System.out.println(x+"->"+y));
        /**
         * summingInt
         */
        Map<String,Integer> map2 = Arrays.stream(students).collect(groupingBy(Student::getName,Collectors.summingInt(Student::getScore)));
        map2.forEach((x,y)-> System.out.println(x+"->"+y));
        /**
         * maxBy
         */
        Map<String,Optional<Student>> map3 = Arrays.stream(students).collect(groupingBy(Student::getName,maxBy(Comparator.comparing(Student::getScore))));
        map3.forEach((x,y)-> System.out.println(x+"->"+y));
        /**
         * mapping
         */
        Map<String,Set<Integer>> map4 = Arrays.stream(students).collect(groupingBy(Student::getName,Collectors.mapping(Student::getScore,Collectors.toSet())));
        map4.forEach((x,y)-> System.out.println(x+"->"+y));
    }


}

本文来源jackaroo2020,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/7054

发表评论