java——Stream flow

insert image description here

Create an immutable collection

What is an immutable collection

  • An immutable collection is a collection that cannot be modified.
  • A collection's data items are provided at creation time and are immutable throughout their lifetime. Otherwise report an error

Why create immutable collections

  • If a certain number cannot be modified, it is good practice to preventively copy it to an immutable collection
  • Or the immutable form is safe when the collection object is not a trusted library utility

How to create immutable collections

  • In the List, Set, and Map interfaces, there is an of method, which can create an immutable collection
    insert image description here
 public static void main(String[] args) {
    
    
        //只需要对数据进行观看,并不需要修改数据
        List<Double> lists= List.of(569.5,700.5,523.0,570.5);
        //lists.add(12.0); 会报错 不可修改
        System.out.println(lists);

        //2.不可变的Set集合
        Set<String> names= Set.of("迪丽热巴","迪丽热九");
        System.out.println(names);

        //2.不可变的Map集合
        Map<String,Integer> maps= Map.of("迪丽热巴",1);
        System.out.println(names);

    }

Stream

What is Stream

Purpose: API for simplifying collection and array operations, combined with Lambda expressions
insert image description here

public static void main(String[] args) {
    
    
        List<String> names=new ArrayList<>();
        Collections.addAll(names,"张小红","小敏","笑话","张敏","张涛");
        System.out.println(names);
        //1.从集合中找出姓张的放到新集合
        List<String> zhanglist=new ArrayList<>();
        for(String name:names){
    
    
            if(name.startsWith("张")){
    
    
                zhanglist.add(name);
            }
        }
        System.out. println(zhanglist);
        //名称长度为3的
        List<String> zhangThreelist=new ArrayList<>();
        for(String name:zhanglist){
    
    
            if(name.length()==3){
    
    
                zhangThreelist.add(name);
            }
        }
        System.out.println(zhangThreelist);

And using Stream one line of code can

        names.stream().filter(s ->s.startsWith("张")).filter(s ->s.length()==3).forEach(s -> System.out.println(s));

The core of the stream thinking:

  1. First get the Stream stream of the collection or array (that is, a conveyor belt)
  2. put the element on
  3. Then use this streamlined API to conveniently manipulate elements.

Get the Stream stream

Get Stream stream

  • Create a pipeline and put data on the pipeline to prepare for operation.
    Intermediate method
  • operations on the pipeline. After one operation is completed, you can continue to perform other operations.
    Termination method
  • A Stream can only have one termination method, which is the last operation on the pipeline. The
    first step in a Stream operation collection or array is to obtain the Stream first, and then use the function
    set of the Stream to obtain the Stream.
  • You can use the default method stream() in the Collaboration interface to produce stream
    insert image description here
    arrays to obtain the Stream stream
    insert image description here
 //Collection集合获取流
        Collection<String> list=new ArrayList<>();
        Stream<String> s=list.stream();
        //Map集合获取流
        Map<String,Integer> maps=new HashMap<>();
        //键流
        Stream<String> keyStream=maps.keySet().stream();
        //值流
        Stream<Integer> valueStream=maps.values().stream();
        //键值对流(拿整体)
        Stream<Map.Entry<String,Integer>> keyAndValueStream=maps.entrySet().stream();
        //数组获取流
        String[] names={
    
    "赵敏","小昭","灭绝","周芷若"};
        //拿到Stream流方法一
        Stream<String> nameStream= Arrays.stream(names);
        //方法二
        Stream<String> nameStream2=Stream.of(names);

Stream common API (intermediate operation method)

insert image description here

  • The intermediate method is also called a non-terminal method. After the call is completed, the returned Stream can continue to be used, and chain programming is supported.
  • Data in collections and arrays cannot be directly modified in Stream.

Common terminal operation methods in Stream

insert image description here
Note: After the operation method is terminated, the stream cannot be used after the call is completed, because the Stream will not be returned

Comprehensive Application of Stream

insert image description here

package com.itheima.stream_test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class StreamDemo04 {
    
    
    public static double allMoney ;
    public static double allMoney2 ; // 2个部门去掉最高工资,最低工资的总和
    public static void main(String[] args) {
    
    
        List<Employee> one = new ArrayList<>();
        one.add(new Employee("猪八戒",'男',30000 , 25000, null));
        one.add(new Employee("孙悟空",'男',25000 , 1000, "顶撞上司"));
        one.add(new Employee("沙僧",'男',20000 , 20000, null));
        one.add(new Employee("小白龙",'男',20000 , 25000, null));

        List<Employee> two = new ArrayList<>();
        two.add(new Employee("武松",'男',15000 , 9000, null));
        two.add(new Employee("李逵",'男',20000 , 10000, null));
        two.add(new Employee("西门庆",'男',50000 , 100000, "被打"));
        two.add(new Employee("潘金莲",'女',3500 , 1000, "被打"));
        two.add(new Employee("武大郎",'女',20000 , 0, "下毒"));

        // 1、开发一部的最高工资的员工。(API)
        // 指定大小规则了
//        Employee e = one.stream().max((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(),  e2.getSalary() + e2.getBonus()))
//                .get();
//       System.out.println(e);
        Topperformer t = one.stream().max((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(),  e2.getSalary() + e2.getBonus()))
                .map(e -> new Topperformer(e.getName(),  e.getSalary() + e.getBonus())).get();
        System.out.println(t);

        // 2、统计平均工资,去掉最高工资和最低工资
        one.stream().sorted((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(),  e2.getSalary() + e2.getBonus()))
                .skip(1).limit(one.size() - 2).forEach(e -> {
    
    
                    // 求出总和:剩余员工的工资总和
                    allMoney += (e.getSalary() + e.getBonus());
                });
        System.out.println("开发一部的平均工资是:" + allMoney / (one.size() - 2));

        // 3、合并2个集合流,再统计
        Stream<Employee> s1 = one.stream();
        Stream<Employee> s2 = two.stream();
        Stream<Employee> s3 = Stream.concat(s1 , s2);
        s3.sorted((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(),  e2.getSalary() + e2.getBonus()))
                .skip(1).limit(one.size() + two.size() - 2).forEach(e -> {
    
    
                    // 求出总和:剩余员工的工资总和
                    allMoney2 += (e.getSalary() + e.getBonus());
                });

        // BigDecimal
        BigDecimal a = BigDecimal.valueOf(allMoney2);
        BigDecimal b = BigDecimal.valueOf(one.size()  + two.size() - 2);
        System.out.println("开发部的平均工资是:" + a.divide(b,2, RoundingMode.HALF_UP));
    }
}

package com.itheima.stream_test;

public class Employee {
    
    
        private String name;
        private char sex;
        private double salary;
        private double bonus;
        private String punish; // 处罚信息

        public Employee(){
    
    
        }

        public Employee(String name, char sex, double salary, double bonus, String punish) {
    
    
            this.name = name;
            this.sex = sex;
            this.salary = salary;
            this.bonus = bonus;
            this.punish = punish;
        }

        public String getName() {
    
    
            return name;
        }

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

        public char getSex() {
    
    
            return sex;
        }

        public void setSex(char sex) {
    
    
            this.sex = sex;
        }

        public double getSalary() {
    
    
            return salary;
        }

        public void setSalary(double salary) {
    
    
            this.salary = salary;
        }

        public double getBonus() {
    
    
            return bonus;
        }

        public void setBonus(double bonus) {
    
    
            this.bonus = bonus;
        }

        public String getPunish() {
    
    
            return punish;
        }

        public void setPunish(String punish) {
    
    
            this.punish = punish;
        }

        public double getTotalSalay(){
    
    
            return salary * 12 + bonus;
        }

        @Override
        public String toString() {
    
    
            return "Employee{" +
                    "name='" + name + '\'' +
                    ", sex=" + sex +
                    ", salary=" + salary +
                    ", bonus=" + bonus +
                    ", punish='" + punish + '\'' +
                    '}'+"\n";
        }

}

package com.itheima.stream_test;

public class Topperformer {
    
    
    private String name;
    private double money; // 月薪

    public Topperformer() {
    
    
    }

    public Topperformer(String name, double money) {
    
    
        this.name = name;
        this.money = money;
    }

    public String getName() {
    
    
        return name;
    }

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

    public double getMoney() {
    
    
        return money;
    }

    public void setMoney(double money) {
    
    
        this.money = money;
    }

    @Override
    public String toString() {
    
    
        return "Topperformer{" +
                "name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

Guess you like

Origin blog.csdn.net/weixin_46362658/article/details/123399093