1, Overview
1. Stream occurrence time: JDK8
2. Function: simplify the API of collection and array operation. Combined with Lambda expression
3. Ideas and usage steps of Stream flow:
(1) get the Stream stream of the set or array first (that is, a conveyor belt)
(2) put the elements on it
(3) then use the simplified API of Stream stream to facilitate the operation of elements
2, Experience Stream flow:
1. We first create a collection object and store some data
List<String> names = new ArrayList<>(); Collections.addAll(names, "Zhang Sanfeng", "zhang wuji", "Zhou Zhixiang", "Zhao Min", "Zhang Qiang"); System.out.println(names);
2. First use the set method to traverse the output
//1. Find the one whose name begins with Zhang List<String> zhangList = new ArrayList<>(); for (String name : names) { if (name.startsWith("Zhang")) { zhangList.add(name); System.out.println(name); } } //2. List<String> zhangThreeList = new ArrayList<>(); for (String name : zhangList) { if(name.length() ==3){ zhangThreeList.add(name); } } System.out.println(zhangThreeList);
3. Use stream output
Preliminarily realize the convenience of recognizing Stream flow
names.stream().filter(s ->s.startsWith("Zhang")).filter(s ->s.length() ==3).forEach(System.out::println);
One line of code handles the above
The unique API of Stream stream is used, which we will talk about below
Filter: filter elements
2, Get (three methods)
1. Get Stream stream
Create a pipeline and put the data on the pipeline for operation
(1) get stream from Collection
Collection<String> list = new ArrayList<>(); Stream<String> s = list.stream();
(2) Map collection acquisition flow
Map<String,Integer> maps = new HashMap<>();
Key flow:
Stream<String> keyStream = maps.keySet().stream();
Value stream:
Stream<Integer> valuesStream = maps.values().stream();
Key value convection (take the whole)
Stream<Map.Entry<String , Integer > > keyAndValuesStream = maps.entrySet().stream();
(3) Array fetch stream
String[] names = {"Zhao Min", "Xiao Zhao", "extinction", "Zhou Zhiruo"}; Stream<String> nameStream = Arrays.stream(names); Stream<String> nameStream2= Stream. of(names);// Two ways of writing
2. Intermediate method
Operations on the pipeline. After one operation, you can continue with other operations
Intermediate methods, also known as non terminating methods, return a new Stream stream after calling, which can continue to be used, and support chain programming
3. Termination method
A Stream stream can only have one termination method, which is the last operation on the pipeline
After the call is completed, it cannot continue to be used because Stream will not be returned
3, Common API (intermediate method)
1. First create a collection and add elements
List<String> list = new ArrayList<>(); list.add("zhang wuji"); list.add("Zhou Zhiruo"); list.add("Zhao Min"); list.add("Zhang Qiang"); list.add("Zhang Sanfeng"); list.add("Zhang Sanfeng");
2. Brief description of common API s
forEach: process one by one (traversal)
Count: count the number
--long count();
Filter: filter element
--Stream<T> filter(Predicate<? super T> predicate)
limit: take the first few elements
Skip: skip the first few elements
map: processing method
concat: merge streams
distinct: removes duplicate elements from the stream. Dependencies (hashCode and equals methods)
Code demonstration:
//Stream<T> filter(Predicate<? super T> predicate) list.stream().filter(s -> s.startsWith("Zhang")).forEach(System.out::println);//Simple method System.out.println(list.stream().filter(s -> s.length() == 3).count());//To save with long size //list. stream(). Filter (s - > s.startswith ("Zhang")) limit(2). forEach(s -> System.out.println(s));// Two ways of writing list.stream().filter(s -> s.startsWith("Zhang")).limit(2).forEach(System.out::println); //Only when the two parameters are the same can the two s be omitted and printed in the form of:: //Map processing method: the first parameter raw material - > the second parameter is the result of processing //Add a black horse to the front of the set elements: list.stream().map(s -> "Dark horse" + s).forEach(System.out::println); //Requirement: process all names into a student object list.stream().map(s -> new Student(s)).forEach(System.out::println); //? Next equation // list.stream().map(Student::new).forEach(System.out::println); // Constructor referenced by method //Merge flow Stream<String> s1 = list.stream().filter(s -> s.startsWith("Zhang")); Stream<String> s2 = Stream.of("Java1","Java2"); // public static <T> Stream<T> concat(Stream <? extends T> a,Stream<? extends T> b) Stream<String> s3 = Stream.concat(s1,s2); s3.forEach(System.out::println); s3.distinct().forEach(System.out::println);
4, Comprehensive application case
Requirements:
*The Development Department of a company is divided into development department I and Development Department II. Now it needs to make mid year data settlement
*Analysis:
*(1) Employee information at least includes (name, gender, salary, bonus and punishment records)
*(2) The first development department has four employees and the second development department has five employees
*(3) Select the highest salary employee information of the two departments and package it into the excellent employee object Topperformer
*(4) The average monthly income of each department shall be counted separately, and the maximum and minimum wages shall be removed
*(5) Make statistics on the overall average wages of the two development departments, excluding the average value of the minimum and maximum wages
1. Create an employee object and make it into a class
package Stream.Test; public class Employee { private String name; private char sex; private double salary; private double bonus; private String punish;//Punishment method 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; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", sex=" + sex + ", salary=" + salary + ", bonus=" + bonus + ", punish='" + punish + '\'' + '}'; } }
2. Create an object for excellent employees and pretend to be a class
package Stream.Test; public class Topperformer { private String name; private double money;//a monthly salary 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 + '}'; } }
3. Topic
public class Test1 { public static double allMoney; public static double allMoney2;//The sum of the two departments excluding the maximum wage and the minimum wage public static void main(String[] args) { List<Employee> one = new ArrayList<>(); one.add(new Employee("Zhu Bajie",'male',30000,25000,null)); one.add(new Employee("Sun WuKong",'male',25000,1000,"Contradict your boss")); one.add(new Employee("Monk Sha",'male',20000,20000,null)); one.add(new Employee("Little white dragon",'male',20000,25000,null)); List<Employee> two = new ArrayList<>(); two.add(new Employee("Wu Song",'male',15000,9000,null)); two.add(new Employee("Li Kui",'male',20000,10000,null)); two.add(new Employee("ximen qing",'male',50000,10000,"Beaten")); two.add(new Employee("Pan Jinlian",'male',3500,1000,"Beaten")); two.add(new Employee("Wu Dalang",'male',2000,0,"Poison")); //1. Develop the highest paid employees of the first department //Size rules have been established //Employee e = one.stream().max((e1,e2) -> Double.compare(e1.getSalary() + e1.getBonus() ,e2.getSalary() + e2.getBonus())) // . get();// Using get method //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.getBonus() + e.getSalary())).get(); System.out.println(t); //Directly in one step and encapsulated into an excellent employee //2. Count the average wage, excluding the maximum and minimum wages one.stream().sorted((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus() ,e2.getSalary() + e2.getBonus())) .skip(1).limit(one.size() - 2).forEach(e -> { //Sum: the sum of the wages of the remaining employees allMoney += (e.getSalary() + e.getBonus()); }); System.out.println("The average salary of development department I is:" + allMoney / (one.size() -2)); //3. Merge two collection streams and make statistics again 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 -> { //Find the total salary of the remaining employees allMoney2 += (e.getBonus() + e.getSalary()); }); //BigDecimal (make the number more accurate) is encapsulated into big data objects BigDecimal a = BigDecimal.valueOf(allMoney2); BigDecimal b = BigDecimal.valueOf(one.size() + two.size() -2); System.out.println(("The average salary of the development department is:" + a.divide(b,2, RoundingMode.HALF_UP)));// // The remainder of b is rounded to two decimal places System.out.println(("The average salary of the development department is:" + allMoney2 / (one.size() + two.size() -2)));// 32071.428571428572 // It's not accurate. There are many decimal places } }
5, Collection (termination method)
Objective: to collect Stream data into a collection or array
Stream stream: a means to facilitate the operation of collections and arrays
Collection, array: is the purpose of development
List<String> list = new ArrayList<>(); list.add("zhang wuji"); list.add("Zhou Zhiruo"); list.add("Zhao Min"); list.add("Zhang Qiang"); list.add("Zhang Sanfeng"); list.add("Zhang Sanfeng");
1. To the List collection
Stream<String> s1 = list. stream(). Filter (s - > s.startswith ("Zhang"); List<String> zhangList = s1. collect(Collectors.toList());// Variable set zhangList.add("java1"); System.out.println(zhangList );
NOTE:
The result is an immutable set (starting from JDK16)
2. To Set collection
Note: the flow can only be used once and cannot be used repeatedly. If the flow is first converted into a List and then into a Set, an error will be reported
Stream<String> s2 = list. stream(). Filter (s - > s.startswith ("Zhang"); Set<String> zhangSet = s2.collect(Collectors.toSet()); System.out.println(zhangSet);
3. Go to the array
Before simplification:
After simplification
Stream<String> s3 = list. stream(). Filter (s - > s.startswith ("Zhang"); //Object[] arrs = s3.toArray(); //String[] arrs = s3.toArray(s -> new String[s]); String[] arrs = s3.toArray(String[]::new );// Finally, the two variables are the same, both of which are s (extension) System. out. Println ("the contents of arrays array are:" + Arrays.toString(arrs));