Java8 stream operation - final operation

What is the final operation?

When we operate on the stream object through the final method, it means that the stream flow operation is also completed, and finally we summarize the object into a result (total number, object, collection...)


method

collect: Summarize (convert) the elements in the Stream into a result, which can be Set, List, Map

reduce: induction, can calculate the sum

Matching: Rule-defined rules to judge the matching of elements and return Boolean type

    • allMatch: Whether to match all
    • anyMatch: any match
    • noneMatch: no match

max&min: returns the largest and smallest elements in the stream through certain comparison rules

count: returns the total number of elements in the stream

forEach: loop


Actual description

1. Preconditions

Person class

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 class

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;
    }
}

Two, operation

collect: Summarize (convert) the elements in the Stream into a result, which can be 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);
    }

output result:


reduce: induction, can calculate the sum

Example 1. Calculate the sum of 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());

output result:

Example 2. Calculate the total score of all students

//获取数据源
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());

output result:


Matching: Rule-defined rules to judge the matching of elements and return Boolean type

    • allMatch: Whether to match all
    • anyMatch: any match
    • noneMatch: no match
//获取数据源
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);

output result:


max&min: returns the largest and smallest elements in the stream through certain comparison rules

//找出成绩最高的对象
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);

output result:


count: returns the total number of elements in the stream

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

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

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

output result:


forEach: loop

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

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

output result:

If you want to exchange content, please leave a message in the comment area . If this document is liked by you, please leave your like + collection + comment footprints to support the blogger~

Guess you like

Origin blog.csdn.net/weixin_43319713/article/details/130462526