当前位置: 代码迷 >> 综合 >> 【2020.07.18】JAVA 流程编程 Stream 中间操作distinct、sorted、limit skip、map、flatmap,最终操作 collect、reduce、max、find
  详细解决方案

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

热度:69   发布时间:2023-12-22 22:30:25.0

流式编程

  • 流程编程
    • 数据源获取
    • 最终操作
    • 中间操作
    • Collectors 工具类

流程编程

数据源获取

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;}@Overridepublic 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);}@Overridepublic int hashCode() {
    return Objects.hash(name, age, score);}@Overridepublic int compareTo(Student o) {
    return score - o.score;}@Overridepublic 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);
    

    }
    }

  相关解决方案