【2020.07.18】JAVA 流程编程 Stream 中间操作distinct、sorted、limit skip、map、flatmap,最终操作 collect、reduce、max、find

流程编程

数据源获取

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @ClassName: DataSource
 * @Author Paulson
 * @Date 2020/7/17
 * @Description: 集合流式编程中数据源的获取
 */
public class DataSource {
    public static void main(String[] args) {
        collectionDataSource();
        arrayDataSource();
        arrayDataSource2();
    }


    /**
     * 将集合作为数据源,读取集合中的数据到一个流中
     */
    public static void collectionDataSource() {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        // 同步流
        Stream<Integer> stream = list.stream();
        // 并发流 (效率更高)
        Stream<Integer> integerStream = list.parallelStream();
        System.out.println(stream);
        System.out.println(integerStream);
    }

    /**
     * 将数组作为数据源,读取集合中的数据到一个流中
     */
    public static void arrayDataSource() {
        Integer[] array = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Stream<Integer> stream = Arrays.stream(array);
        System.out.println(stream);
    }

    /**
     * 将数组作为数据源,读取集合中的数据到一个流中
     */
    public static void arrayDataSource2() {
        int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        IntStream stream = Arrays.stream(array);
        System.out.println(stream);
    }

}

最终操作

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

/**
 * @ClassName: FinalOperation
 * @Author Paulson
 * @Date 2020/7/17
 * @Description: 最终操作
 */
public class FinalOperation {
    public static void main(String[] args) {
        // colloctUsage();
        // reduceUsage();
        // countUsage();
        // forEachUsage();
        // MaxAndMinUsage();
        // matchUsage();
        // findUsage();
        IntStreamUsage();
    }

    /**
     * IntStream
     */
    public static void IntStreamUsage() {
        int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        IntStream stream = Arrays.stream(array);
        // OptionalInt result = stream.max();
        // OptionalInt result = stream.min();
        // System.out.println(result.orElse(-1));

        // int result = stream.sum();
        // long result = stream.count();
        // double result = stream.average().getAsDouble();
        // System.out.println(result);

        // 对流中的数据进行分析
        IntSummaryStatistics intSummaryStatistics = stream.summaryStatistics();
        System.out.println("max = " + intSummaryStatistics.getMax());
        System.out.println("min = " + intSummaryStatistics.getMin());
        System.out.println("sum = " + intSummaryStatistics.getSum());
        System.out.println("average = " + intSummaryStatistics.getAverage());
        System.out.println("count = " + intSummaryStatistics.getCount());
    }


    /**
     * findFirst 从流中获取开头元素
     * findAny 从流中获取元素(一般是开头元素) 在多线程的环境下,可能不是开头元素
     */
    public static void findUsage() {
        // Stream<Integer> dataSource = getDataSource();
        // Optional<Integer> result = dataSource.findFirst();
        // Optional<Integer> result = dataSource.findAny();


        List<Integer> dataSourse = new ArrayList<>();
        Collections.addAll(dataSourse, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        Optional<Integer> result = dataSourse.parallelStream().findAny();

        System.out.println(result.orElse(null));
    }

    /**
     * allMatch anyMatch noneMatch
     */
    public static void matchUsage() {
        Stream<Integer> dataSource = getDataSource();
        // boolean result = dataSource.allMatch(e -> e >= 0);
        // boolean result = dataSource.anyMatch(e -> e >= 9);
        boolean result = dataSource.noneMatch(e -> e > 9);
        System.out.println(result);
    }

    /**
     * max and min
     * 按照指定的对象比较的规则,进行大小比较,得出流中最大或最小的元素
     */
    public static void MaxAndMinUsage() {
        Stream<Integer> dataSource = getDataSource();
        // Optional<Integer> result = dataSource.max(Integer::compareTo);
        Optional<Integer> result = dataSource.min(Integer::compareTo);
        System.out.println(result.orElse(0));

    }

    /**
     * forEach
     * 遍历流中数据
     */
    public static void forEachUsage() {
        Stream<Integer> dataSource = getDataSource();
        dataSource.forEach(System.out::println);
    }

    /**
     * 统计流中数据的数量
     */
    public static void countUsage() {
        Stream<Integer> dataSource = getDataSource();
        long count = dataSource.count();
        System.out.println(count);
    }

    /**
     * reduce
     * 将流中的数据按照一定的规则聚合起来
     */
    public static void reduceUsage() {
        Stream<Integer> dataSource = getDataSource();
        Optional<Integer> reduce = dataSource.reduce(Integer::sum);
        System.out.println(reduce.orElse(0));
    }

    /**
     * 最终操作
     * collect 将流中的数据整起来,最常见的处理是:读取流中的数据,整个到一个容器中,得到一个集合
     */
    public static void colloctUsage() {

        Stream<Integer> dataSource = getDataSource();
        // List<Integer> collect = dataSource.collect(Collectors.toList());
        // Set<Integer> collect = dataSource.collect(Collectors.toSet());
        Map<String, Integer> collect = dataSource.collect(Collectors.toMap(Object::toString, i -> i));

        System.out.println(collect);
    }

    /**
     * 数据源的获取,从一个容器中获取数据源中的数据
     *
     * @return 读取数据源中的数据,得到的一个 Stream 对象
     */
    public static Stream<Integer> getDataSource() {
        List<Integer> dataSourse = new ArrayList<>();
        Collections.addAll(dataSourse, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        return dataSourse.stream();
    }


}

中间操作

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

/**
 * @ClassName: ProcessOperation
 * @Author Paulson
 * @Date 2020/7/18
 * @Description: 流式编程的中间操作
 */
public class ProcessOperation {

    /**
     * 学生类
     * 存储于集合中数据类型
     */
    private static class Student implements Comparable<Student> {
        private String name;
        private Integer age;
        private Integer score;

        public Student(String name, Integer age, Integer score) {
            this.name = name;
            this.age = age;
            this.score = score;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public Integer getScore() {
            return score;
        }

        public void setScore(Integer score) {
            this.score = score;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Student student = (Student) o;
            return Objects.equals(name, student.name) &&
                    Objects.equals(age, student.age) &&
                    Objects.equals(score, student.score);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, age, score);
        }

        @Override
        public int compareTo(Student o) {
            return score - o.score;
        }


        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", score=" + score +
                    '}';
        }
    }

    public static void main(String[] args) {
        // filterUsage();
        // distinctUsage();
        // sortedUsage();
        // limitAndSkipUsage();
        // mapUsage();
        flatmapUsage();
    }

    /**
     * 读取数据源
     *
     * @return 从数据源中读取到的数据
     */
    public static Stream<Student> getDataSource() {
        List<Student> arrayList = new ArrayList<>();
        Collections.addAll(arrayList, new Student("小明", 18, 90),
                new Student("xiaohong", 19, 90),
                new Student("xiaohong", 20, 60),
                new Student("xiaohong", 18, 98),
                new Student("xiaohong", 17, 56),
                new Student("xiaohong", 21, 56),
                new Student("xiaohong", 20, 34),
                new Student("xiaohong", 22, 75),
                new Student("xiaohong", 21, 98),
                new Student("xiaohong", 28, 100),
                new Student("xiaobao", 28, 100),
                new Student("xiaobao", 28, 100),
                new Student("xiaohong", 15, 23)
        );
        return arrayList.stream();

    }

    /**
     * 中间操作:flatmap
     * 扁平化映射:一般用在map映射完成后,流中的数据是一个容器,而我们需要对容器中的数据进行处理
     * 此时使用扁平化映射
     */
    public static void flatmapUsage() {
        String[] array = {"hello", "world"};
        Stream<String> stream = Arrays.stream(array);
        // stream.map(String::toCharArray).forEach(e -> System.out.println(Arrays.toString(e)));
        stream.map(s -> s.split(""))
                .flatMap(Arrays::stream)
                .forEach(System.out::println);
    }

    /**
     * 中间操作:map
     * 元素映射:提供一个映射规则,将流中的每一个元素替换成指定的元素
     */
    public static void mapUsage() {
        Stream<Student> dataSource = getDataSource();
        // 获取所有学生的名字
        // dataSource.map(Student::getName).forEach(System.out::println);

        // 获取所有的成绩
        dataSource.map(Student::getScore).forEach(System.out::println);
    }

    /**
     * 中间操作:sorted
     * 排序
     * sorted() 将流中的数据按照其对应的类实现的Comparable接口提供的比较奥尼规则进行排序
     * sorted(Comparator<T> comparator) 将流中的数据按照昂参数接口提供的比较规则进行排序
     */
    public static void sortedUsage() {
        Stream<Student> dataSource = getDataSource();
        // dataSource.sorted().forEach(System.out::println);
        dataSource.sorted(Comparator.comparingInt(Student::getAge)).forEach(System.out::println);
    }

    /**
     * 中间操作:limit skip
     * limit:限制,表示截取流中的指定数量的数据
     * skip:跳过指定数量的数据,截取剩余部分
     */
    public static void limitAndSkipUsage() {
        Stream<Student> dataSource = getDataSource();
        // 获取成绩前3-5名
        dataSource.sorted((s1, s2) -> s2.getScore() - s1.getScore())
                .distinct()
                .skip(2)
                .limit(3)
                .forEach(System.out::println);
    }

    /**
     * 中间操作:distinct
     * 去重:无参,去重规则与hashSet相同
     * 1. hashcode
     * 2. equals
     */
    public static void distinctUsage() {
        Stream<Student> dataSource = getDataSource();
        dataSource.distinct().forEach(System.out::println);
    }

    /**
     * 中间操作:filter
     * 条件过滤: 将流中满足指定条件的数据保留,删除不满足指定条件的数据
     */
    public static void filterUsage() {
        Stream<Student> dataSource = getDataSource();
        // 过滤掉不及格的信息
        dataSource.filter(s -> s.getScore() >= 60).forEach(System.out::println);

    }

}

Collectors 工具类

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**

  • @ClassName: CollectorsUsage

  • @Author Paulson

  • @Date 2020/7/18

  • @Description:
    */
    public class CollectorsUsage {

    public static void main(String[] args) {

     String[] array = {"hello", "world", "bigDate", "salary", "goodProgrammer"};
     Stream<String> stream = Arrays.stream(array);
    
     // joining方法,只适用于Stream<String>
     // String result = stream.collect(Collectors.joining());
     // String result = stream.collect(Collectors.joining(", ", "[", "]"));
    
     // int result = stream.mapToInt(String::length).sum();
     // IntSummaryStatistics result = stream.collect(Collectors.summarizingInt(String::length));
     List<String> result = stream.collect(Collectors.toList());
     System.out.println(result);
    

    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值