Java8流式操作——最终操作

什么是最终操作?

当我们通过最终方法对流对象进行操作,说明stream流操作也完成,最后我们将对象汇总成一个结果(总数、对象、集合……)


方法

collect:将Stream中的元素汇总(转化)成一个结果,可以是Set、List、Map

reduce:归纳,可以计算总和

Matching:规矩自定义的规则判断元素的匹配情况,返回布尔类型

    • allMatch:是否全部匹配
    • anyMatch:任意一个匹配
    • noneMatch:没有匹配

max&min:通过一定的比较规则,返回stream中最大元素和最小元素

count:返回stream中元素的总个数

forEach:循环


实战说明

一、前提条件

Person类

package com.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * @BelongsProject: StreamOperate
 * @BelongsPackage: com.example
 * @CreateTime: 2023-05-01  11:18
 * @Description: Person实体类
 * @Version: 1.0
 */
public class Person implements Comparable<Person>{
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public Person setAge(int age) {
        this.age = age;
        return this;
    }

    public int getScore() {
        return score;
    }

    public Person setScore(int score) {
        this.score = score;
        return this;
    }

    private String name;
    private int age;
    private int score;


    public Person(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Person() {

    }

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

    @Override
    public boolean equals(Object o) {
        //地址相同,为true
        if (this == o) return true;
        //为null,并且类型不一样,为false
        if (o == null || getClass() != o.getClass()) return false;
        //向下转型,再去比较属性值
        Person person = (Person) o;
        //如果属性值相同,最后的结果为true
        return age == person.age && score == person.score && Objects.equals(name, person.name);


        //return false;
    }

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


    @Override
    public int compareTo(Person o) {
        return this.getScore()-o.getScore();
    }
}

Data类

package com.example;

import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;

/**
 * @BelongsProject: StreamOperate
 * @BelongsPackage: com.example
 * @CreateTime: 2023-05-01  11:08
 * @Description: Data类
 * @Version: 1.0
 */
public class Data {
    public static ArrayList<Person> getData() {
        ArrayList<Person> personList = new ArrayList<>();

        personList.add(new Person("张三", 18, 90));
        personList.add(new Person("李四", 19, 100));
        personList.add(new Person("王五", 17, 60));
        personList.add(new Person("赵六", 18, 89));
        personList.add(new Person("孙七", 20, 96));
        personList.add(new Person("郑十", 20, 46));
        personList.add(new Person("周八", 20, 96));
        personList.add(new Person("吴九", 20, 45));
        personList.add(new Person("邓十一", 20, 35));
        personList.add(new Person("刘十二", 20, 99));
        personList.add(new Person("小十三", 20, 56));

        return personList;
    }
}

二、操作

collect:将Stream中的元素汇总(转化)成一个结果,可以是Set、List、Map

	/**
     * @Description:最终操作——collection方法	
     * @Date: 2023/5/1 11:32
     * @return: void
     **/
    public void test() {
        Stream<Person> stream = Data.getData().stream();

        //转化为List集合
        List<Person> list = stream.collect(Collectors.toList());
        //转化成Set集合
        Set<Person> set = stream.collect(Collectors.toSet());
        //转化成Map集合
        Map<String, Integer> maps = stream.collect(Collectors.toMap(Person::getName, Person::getScore));

        //输出结果
        System.out.println(list);
        System.out.println("--------------------------------------------------------------------------");
        System.out.println(set);
        System.out.println("--------------------------------------------------------------------------");
        System.out.println(maps);
    }

输出结果:


reduce:归纳,可以计算总和

实例一、计算1-10的和

//声明一个stream对象
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

//累加计算和
Optional<Integer> ret = stream1.reduce((n1, n2) -> n1 + n2);

//输出结果
System.out.println(ret.get());

输出结果:

实例二、计算所有学生的总成绩

//获取数据源
Stream<Person> stream = Data.getData().stream();

//计算总成绩
Optional<Person> reduce = stream.reduce((n1, n2) -> new Person().setScore(n1.getScore() + n2.getScore()));

//输出总成绩
System.out.println(reduce.get().getScore());
通过实例我们会发现每次执行reduce都会产生很多临时对象,这样是很损耗性能的,我们可以通过实例化一个对象固定,这样就不会实例化很多临时对象.

//实例化一个临时对希望
Person tmp = new Person();

//计算总成绩
Optional<Person> reduce1 = stream.reduce((n1, n2) -> tmp.setScore(n1.getScore() + n2.getScore()));

//输出总成绩
System.out.println(reduce1.get().getScore());

输出结果:


Matching:规矩自定义的规则判断元素的匹配情况,返回布尔类型

    • allMatch:是否全部匹配
    • anyMatch:任意一个匹配
    • noneMatch:没有匹配
//获取数据源
Stream<Person> stream = Data.getData().stream();

//判断集合中是否包含成绩大于80的人员
boolean result1 = stream.allMatch(ele -> ele.getScore() > 80);
System.out.println("allMatch:"+result1);

//判断集合中是否所有的成员成绩都及格
boolean result2 = stream.anyMatch(ele -> ele.getScore() >= 60);
System.out.println("anyMatch:"+result2);

//判断集合中是否所有的成员成绩都及格
boolean result3 = stream.noneMatch(ele -> ele.getScore() <= 60);
System.out.println("noneMatch:"+result3);

输出结果:


max&min:通过一定的比较规则,返回stream中最大元素和最小元素

//找出成绩最高的对象
Optional<Person> max = Data.getData().stream().max((ele1, ele2) -> ele1.getScore() - ele2.getScore());
System.out.println(max);

//找出成绩最低的对象
Optional<Person> min = Data.getData().stream().min((ele1, ele2) -> ele1.getScore() - ele2.getScore());
System.out.println(min);

输出结果:


count:返回stream中元素的总个数

//获取数据源
Stream<Person> stream = Data.getData().stream();

//返回总个数
long count = stream.count();

//输出结果
System.out.println(count);

输出结果:


forEach:循环

//获取数据源
Stream<Person> stream = Data.getData().stream();

//循环输出集合对象
stream.forEach(System.out::println);

输出结果:

如果有想要交流的内容欢迎在评论区进行留言,如果这篇文档受到了您的喜欢那就留下你点赞+收藏+评论脚印支持一下博主~

猜你喜欢

转载自blog.csdn.net/weixin_43319713/article/details/130462526