一念花开~

导航

 

 

 

package com.tdlx.springboot_shiro_jwt.syscommon.utils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.*;

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

//当循环遍历中不需要进行数据库操作时,使用stream()或普通循环来遍历(根据实际业务情况来选择用哪个)。
//当循环遍历中(多次循环,百次以上)需要进行数据库操作时,使用parallelStream()来遍历,但是要注意多线程安全
public class Streams {
    public static void main(String[] args) {
        streanFlatMap();
    }


    //3.6 FlatMap 流的扁平化处理
    public static void streanFlatMap() {
        List<List<Integer>> outer = new ArrayList<>();
        List<Integer> inner1 = new ArrayList<>();
        inner1.add(1);
        List<Integer> inner2 = new ArrayList<>();
        inner1.add(2);
        List<Integer> inner3 = new ArrayList<>();
        inner1.add(3);
        List<Integer> inner4 = new ArrayList<>();
        inner1.add(4);
        List<Integer> inner5 = new ArrayList<>();
        inner1.add(5);
        outer.add(inner1);
        outer.add(inner2);
        outer.add(inner3);
        outer.add(inner4);
        outer.add(inner5);
        //把流中集合装换为流
        List<Integer> result = outer.stream().flatMap(inner -> inner.stream().map(i -> i + 1)).collect(toList());
        System.out.println(result);
        System.out.println("############");

        String[] strings = {"Hello", "World"};
        //分步写(流只能消费一次)(flatMap)
        Stream<String[]> stream1 = Arrays.asList(strings).stream().
                map(str -> str.split(""));
        //把流中的String[]转换成流
        Stream<String> stringStream = stream1.flatMap(strings1 -> Arrays.stream(strings1));
        List<String> stringList1 = stringStream.collect(toList());
        stringList1.stream().forEach(System.out::println);
        System.out.println("############");
    }
    //3.5 Collectors
    /*public static void streanCollectors() {

        Student s1 = new Student("aa", 10, 1);
        Student s2 = new Student("bb", 20, 2);
        Student s3 = new Student("cc", 10, 3);
        List<Student> list = Arrays.asList(s1, s2, s3);

        //装成list
        List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]

        //转成set
        Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]

        //转成map,注:key不能相同,否则报错
        Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}

        //字符串分隔符连接
        String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)

        //聚合操作
        //1.学生总数
        Long count = list.stream().collect(Collectors.counting()); // 3
        //2.最大年龄 (最小的minBy同理)
        Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
        //3.所有人的年龄
        Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
        //4.平均年龄
        Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
        // 带上以上所有方法
        DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
        System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());

        //分组
        Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
        //多重分组,先根据类型分再根据年龄分
        Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));

        //分区
        //分成两部分,一部分大于10岁,一部分小于等于10岁
        Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));

        //规约
        Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //4
    }*/

    //3.4 流的消费 如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;
    // 而peek接收的是Consumer表达式,没有返回值。
    /*public static void streanMatch() {

        Student s1 = new Student("aa", 10);
        Student s2 = new Student("bb", 20);
        List<Student> studentList = Arrays.asList(s1, s2);

        studentList.stream()
                .peek(o -> o.setAge(100))
                .forEach(System.out::println);

    //结果:
        Student{name='aa', age=100}
        Student{name='bb', age=100}
    }*/
    //3.3 流的匹配 anyMatch(任何一个元素匹配,返回 true)、
    // allMatch(所有元素匹配,返回 true)、noneMatch(没有一个元素匹配,返回 true)
    public static void streanMatch() {
        boolean b = Stream.of(1, 2, 3, 4, 5, 10)
                .anyMatch(x -> x > 5);
        System.out.println(b);
        System.out.println("##################");

        boolean b2 = Stream.of(1, 2, 3, 4, 5, 10)
                .allMatch(x -> x > 5);
        System.out.println(b2);
        System.out.println("##################");

        boolean b3 = Stream.of(1, 2, 3, 4, 5, 10)
                .noneMatch(x -> x > 5);
        System.out.println(b3);
    }

    //3.2 流的查找 findFirst() findAny()
    public static void streanFind() {
        String[] strings = {"hello", "sihai", "hello", "Java8"};
        Optional<String> first = Arrays.stream(strings)
                .findFirst();
        System.out.println(first.get());
        System.out.println("##################");

        Optional<String> any = Arrays.stream(strings).findAny();
        System.out.println(any.get());
        System.out.println("##################");
//错误
//        Optional<Object> any2 = Arrays.asList().stream().findAny();
//        System.out.println(any2.get());
//        System.out.println("##################");
    }
    //3.1 流的操作
//Intermediate(中间)(并没有真正开始流的遍历):一个流可以后面跟随零个或多个 intermediate 操作。
//其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。
//这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历。
//Terminal(终端)(真正开始流的遍历):一个流只能有一个 terminal 操作,当这个操作执行后,流就被使用“光”了,无法再被操作。所以这必定是流的最后一个操作。
//Terminal 操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个 side effect。
//Intermediate:map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
//Terminal:forEach、forEachOrdered、toArray、reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
//Short-circuiting:anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit

    public static void operate() {

        String[] strings = {"hello", "sihai", "hello", "Java8"};

        Stream<String> stream = Arrays.stream(strings);//Stream 只能被使用一次

        //filter过滤 对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream。
        Stream<String> o = stream.filter(x -> x.contains("o"));
        o.forEach(System.out::println);
        System.out.println("filter##################");

        //map  把 input Stream 的每一个元素,映射成 output Stream 的另外一个元素。
        Arrays.stream(strings)
                .map(String::toUpperCase)
                .forEach(System.out::println);
        Stream.of(1, 2, 3).
                map(Integer -> Integer * Integer)
                .forEach(System.out::println);
        System.out.println("map##################");

        //distinct去重
        Stream<String> distinct = Arrays.stream(strings).distinct();
        distinct.forEach(System.out::println);
        System.out.println("distinct##################");

        //limit 截取 截取前面两个单位:
        Arrays.stream(strings).limit(2).forEach(System.out::println);
        System.out.println("limit##################");

        //skip 跳过 跳过前面两个单位:
        Arrays.stream(strings).skip(2).forEach(System.out::println);
        System.out.println("skip##################");

        //计数 2种方式
        long count = Arrays.stream(strings)
                .count();
        System.out.println(count);
        //数组转集合 转为流  计数改为集合计数
        Long collect = Arrays.asList(strings).stream().collect(Collectors.counting());
        System.out.println(collect);
        System.out.println("count##################");

        //求和
        int sum = Arrays.stream(strings)
                .mapToInt(String::length)
                .sum();
        System.out.println(sum);
        System.out.println("sum##################");

        //平均数
        OptionalDouble average = Arrays.stream(strings)
                .mapToInt(String::length)
                .average();
        System.out.println(average);
        System.out.println("average##################");

        //最大值
        OptionalInt max = Arrays.stream(strings)
                .mapToInt(String::length)
                .max();
        System.out.println(max);
        System.out.println("max##################");

        //最小值
        OptionalInt min = Arrays.stream(strings)
                .mapToInt(String::length)
                .min();
        System.out.println(min);
        System.out.println("min##################");
    }

    //2.4 流的连接 concat flatMap
    public static void testConcatStream() {
        //两个流的连接 使用 Stream.concat 方法,
        Stream<String> first = Stream.of("sihai", "sihai2", "sihai3");
        Stream<String> second = Stream.of("sihai4", "sihai5", "sihai6");
        Stream<String> third = Stream.of("siha7", "sihai8", "sihai9");
        Stream<String> concat = Stream.concat(first, second);

        //多个流的连接 使用 Stream.flatMap 方法
        Stream<String> stringStream = Stream.of(first, second, third).flatMap(Function.identity());

    }

    //2.3 一个集合的对象的某一个字段取出来,然后再存到另外一个集合中
    public static void fieldStrean() {
        //映射出名字
        //List<String> strings = list.stream().map(Person::getName).collect(Collectors.toList());
    }

    //2.2字符串和流的装换
    public static void stringStream() {
        //1.codePoints()
        String s = "hello world Java8".codePoints()//转换成流
                .collect(StringBuffer::new,
                        StringBuffer::appendCodePoint,
                        StringBuffer::append)//将流转换为字符串
                .toString();
        System.out.println(s);
        //2.chars()
        String s1 = "hello world Java8".chars()//转换成流
                .collect(StringBuffer::new,
                        StringBuffer::appendCodePoint,
                        StringBuffer::append)//将流转换为字符串
                .toString();
    }

    //2.1流转集合  装箱流  基本数值型目前有三种对应的包装类型:IntStream、LongStream、DoubleStream
    public static void boxStream() {
        //1.一般格式 将流的数据收集为基本类型的集合
        //Stream.collect(Collectors.toList())
        List<Double> collect2 = Stream.of(1.0, 2.0, 3.0).collect(toList());

        //2.通用格式
        List<Double> list = Stream.of(1.0, 2.0, 3.0)
                .collect(ArrayList<Double>::new, ArrayList::add, ArrayList::addAll);
        // 第一个参数:使用一个静态方法初始化一个 List 容器;
        // 第二个参数:使用静态方法 add ,添加元素;
        // 第三个参数:使用静态方法 addAll ,用于联合所有的元素。
        System.out.println("############");


        //3.boxed Double
        List<Double> collect = DoubleStream.of(1.0, 2.0, 3.0)
                .boxed()
                .collect(toList());
        System.out.println("############");

        //4.mapToObj Double
        List<Double> collect1 = DoubleStream.of(1.0, 2.0, 3.0)
                .mapToObj(Double::valueOf)
                .collect(toList());
        System.out.println("############");

    }

    //1.1流的创建 4种 of,iterate,generate,集合
    public static void createStream() {

        //1.利用Stream.of方法创建流  参数很简单,就是一系列的泛型参数。
        Stream<String> stringStream = Stream.of("中国", "美国", "加拿大");
        stringStream.forEach(System.out::println);
        System.out.println("############");

        //2.利用Stream.iterate方法创建流 第一个参数是一个初始值,第二个参数是一个操作。
        java.util.stream.Stream.iterate(10, n -> n + 1)
                .limit(5)
                .collect(toList())
                .forEach(System.out::println);
        System.out.println("##################");

        //3.利用Stream.generate方法创建流
        java.util.stream.Stream.generate(Math::random)
                .limit(5)
                .forEach(System.out::println);
        System.out.println("##################");

        //4.从现有的集合中创建流
        List<String> strings = Arrays.asList("hello", "world", "Java8");
        String string = strings.stream().collect(Collectors.joining(","));
        System.out.println(string);
        //5.数组中创建流
        String[] stringss = {"hello", "sihai", "hello", "Java8"};
        Stream<String> stream = Arrays.stream(stringss);
        //6.文件中创建流
        //Stream<String> file = Files.lines(Paths.get("D:\\zhangkai\\WorkSpace\\Git\\hexo\\_config.yml"));
    }

    //1.2归约操作(流的转换) 转换为集合、数组、字符串等
    public void streamToOther() {
        Stream<String> stream = Stream.of("15", "25", "35");
        // 1. Array
        String[] strArray1 = stream.toArray(String[]::new);
        // 2. Collection
        List<String> list1 = stream.collect(toList());
        List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
        Set set1 = stream.collect(Collectors.toSet());
        Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
        // 3. String
        String str = stream.collect(Collectors.joining()).toString();

    }
}

 

posted on 2019-09-25 15:07  一念花开~  阅读(883)  评论(0)    收藏  举报