Java8 feature: Stream efficient operation of array collection

Introduction

Stream, as a new feature of java8, is based on lambda expressions and is an enhancement to the function of collection objects. It focuses on various efficient and convenient aggregation operations or mass data operations on collection objects, which improves programming efficiency and code readability. Sex.

The principle of Stream: The element to be processed is regarded as a stream. The stream is transmitted in the pipeline and can be processed on the nodes of the pipeline, including filtering, deduplication, sorting, and aggregation. The element flow is processed by intermediate operations in the pipeline, and finally the result of the previous processing is obtained from the final operation.
There are two ways to generate streams for collections: The
Insert picture description here
above figure is the class structure diagram of the Stream class, which contains most of the intermediate and termination operations.

for example

First, in order to explain the operation of Stream on the collection of objects, create a new Student class (student class), overwrite the equals() and hashCode() methods

public class Student1{
    
    

    private Long id;
    private String name;
    private int age;
    private String address;

    
   public Student1(){
    
    }

  public Student1(Long id,String name,int age,String address)
 {
    
    
        this.id =id;
        this.name =name;
        this.age =age;
        this.address =address;
    }

    
	@Override
   public String toString() {
    
    
        return "Student1{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }

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

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

    public Long getId() {
    
    
        return id;
    }

    public void setId(Long id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

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

    public int getAge() {
    
    
        return age;
    }

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

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

}

filter

public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    
        Student1 s1 = new Student1(1L, "张三", 15, "浙江");
        Student1 s2 = new Student1(2L, "李四", 15, "湖北");
        Student1 s3 = new Student1(3L, "王五", 17, "北京");
        Student1 s4 = new Student1(4L, "赵六", 17, "浙江");
        List<Student1> student1s = new ArrayList<>();
        student1s.add(s1);
        student1s.add(s2);
        student1s.add(s3);
        student1s.add(s4);

        List<Student1> streamStudents = testFilter(student1s);
        streamStudents.forEach(System.out::println);

    }
    private static List<Student1>testFilter(List<Student1>student1s){
    
    
        //筛选年龄大于15岁的学生
//        return student1s.stream().filter(s->s.getAge()>15).collect(Collectors.toList());
//        //筛选住在浙江的学生
        return student1s.stream().filter(s->"浙江".equals(s.getAddress())).collect(Collectors.toList());
    }

Operation result:
Insert picture description here
Here we have created four students. After filtering, the group of students whose address is Zhejiang is filtered out.

map (conversion)

  public static void main(String[] args) {
    
    
        Student1 s1 = new Student1(1L, "张三", 15, "浙江");
        Student1 s2 = new Student1(2L, "李四", 15, "湖北");
        Student1 s3 = new Student1(3L, "王五", 17, "北京");
        Student1 s4 = new Student1(4L, "赵六", 17, "浙江");
        List<Student1> student1s = new ArrayList<>();
        student1s.add(s1);
        student1s.add(s2);
        student1s.add(s3);
        student1s.add(s4);
        
        testMap(student1s);
    }
    private static void testMap(List<Student1>student1s){
    
    
        //地址前面加上部分.信息,只获取地址输出
        List<String> addresses = student1s.stream().map(s -> "地址:" + s.getAddress()).collect(Collectors.toList());
        addresses.forEach(a-> System.out.println(a));
    }

Operation result:
Insert picture description here
map is to transform the corresponding element according to the given method.

distinct (de-duplication)

Insert picture description here
Operation result:
Insert picture description here
Insert picture description here
Operation result: It
Insert picture description here
can be seen that the two repeated "Li Si" and "Zhao Liu" students have performed deduplication, not only because the distinct() method is used, but also because the Student object rewrites equals and hashCode( ) Method, otherwise deduplication is invalid.

sorted

Insert picture description here
Operation result:
Insert picture description here
Insert picture description here
Operation result: The
Insert picture description here
sorting rules specified above, first sort in descending order according to student id, and then sort in descending order according to age

limit (limit the number of returns)

Insert picture description here
operation result:
Insert picture description here

skip (remove element)

Insert picture description here
operation result:
Insert picture description here

min (seeking the minimum value)

Insert picture description here
Operation result: The
Insert picture description here
above is to find the youngest one among all the students, max is the same, find the maximum value.

to sum up

The above introduced some methods commonly used by Stream. Although the traversal and operation of the collection can be done in the usual way, when the business logic is complicated, you will find that the amount of code is a lot, the readability is poor, and it is clear that one line of code solves the problem , But you wrote several lines. Try lambda expression, try Stream, you will have a different experience.

Guess you like

Origin blog.csdn.net/weixin_46011971/article/details/106988505
Recommended