The Stream flow
A Stream is a queue of elements from a data source and supports aggregation operations:
- Elements are objects of a specific type that form a queue. A Stream in Java does not store elements, but evaluates on demand.
- Data source Indicates the source of the flow. It could be collections, arrays, etc.
- Aggregation operations are similar to SQL statements, such as filter, Map, reduce, find, match, sorted, and so on.
The three steps of a Stream operation are:
-
Create a Stream
A data source (e.g., collection, array) that retrieves a stream
-
In the middle of operation
An intermediate chain of operations that processes data from the data source
-
Termination of operations
A termination operation that performs an intermediate chain of operations and produces a result
To create a Stream:
- Sequential streams stream() or parallel streams parallelStream() provided by Collection family collections
- Get the data stream from the static method stream() in Arrays
- Through the static method of() in the Stream class
Example code:
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; Public class StreamTest01 {public static void main(String[] args) { Stream List<String> List = array.asList (" Red Wolf "," Grey Wolf "," Happy Sheep "); Stream<String> stream=list.stream(); // Create Stream<String> stream2 = list.parallelstream (); Java.util. Arrays creates stream Integer[] Integer =new Integer[]{1,2,4}; Stream<Integer> stream3 = array.stream (Integer); // Array.stream (Integer); // Create streams indirectly by calling the Stream () static method Stream<String> stream4= stream.of ("a","b","c"); }}Copy the code
Intermediate operation of Stream
Screening and slicing
-Leonard: Filter.
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StramTest02 { public static void main(String[] args) { Employee employee01=new Employee("yang","hui",29); Employee employee02=new Employee("yang","hui",49); Employee employee03=new Employee("yang","hui",9); Employee employee04=new Employee("yang","hui",89); Employee employee05=new Employee("yang","hui",89); Employee employee06=new Employee("yang","hui",89); List<Employee> list= Arrays.asList(employee01,employee02,employee03,employee04,employee05,employee06); Stream1 = list.stream(); // Create Stream<Employee> stream1 = list.stream(); / / to filter stream1 flow Stream < Employee > s = stream1. Filter ((e) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the filter -- -- -- -- -- -- -- -- -- -- -- -- "); Return LLDB etAge() >= 19; }); s.forEach((e-> System.out.println(e))); } } class Employee { private String id; private String name; private int age; public Employee() { } public Employee(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String 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; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() ! = o.getClass()) return false; Employee employee = (Employee) o; return age == employee.age && id.equals(employee.id) && name.equals(employee.name); } @Override public String toString() { return "Employee{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code
Running results:
Skip (n): refers to skip the first n data stored in the Stream (including the NTH data) and return the last n data. If n is greater than the number of all elements in the Stream, null will be returned. (Employee as above)
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StramTest02 { public static void main(String[] args) { Employee employee01=new Employee("yang","hui",9); Employee employee02=new Employee("yang","hui",49); Employee employee03=new Employee("yang","hui",9); Employee employee04=new Employee("yang","hui",89); Employee employee05=new Employee("yang","hui",89); Employee employee06=new Employee("yang","hui",89); List<Employee> list= Arrays.asList(employee01,employee02,employee03,employee04,employee05,employee06); Stream1 = list.stream(); // Create Stream<Employee> stream1 = list.stream(); / / to filter stream1 flow Stream < Employee > s = stream1. Filter ((e) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the filter -- -- -- -- -- -- -- -- -- -- -- -- "); Return LLDB etAge() >= 19; }).skip(2); //s=s.skip(5); s.forEach((e-> System.out.println(e))); }}Copy the code
Run screenshot:
Distinct: Filter for duplicate elements, removing duplicate elements by hashCode() and equals of stream production elements;
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Stream; public class StramTest02 { public static void main(String[] args) { Employee employee01=new Employee("yang","hui",9); Employee employee02=new Employee("yang","hui",49); Employee employee03=new Employee("yang","hui",9); Employee employee04=new Employee("yang","hui",89); Employee employee05=new Employee("yang","hui",89); Employee employee06=new Employee("yang","hui",89); List<Employee> list= Arrays.asList(employee01,employee02,employee03,employee04,employee05,employee06); Stream1 = list.stream(); // Create Stream<Employee> stream1 = list.stream(); / / to filter stream1 flow Stream < Employee > s = stream1. Filter ((e) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the filter -- -- -- -- -- -- -- -- -- -- -- -- "); Return LLDB etAge() >= 19; }).skip(2).distinct(); //s=s.skip(5); s.forEach((e-> System.out.println(e))); }}Copy the code
Run screenshot:
Sorting:
Sorted (Comparable) – Natural sort
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StreamTest03 { public static void main(String[] args) { List<String> list= Arrays.asList("c","bbb","abc","bbbb"); Stream<String> stream = list.stream(); Sorted () = stream= stream.sorted(); // Get sorted() = stream= stream.sorted(); stream.forEach(System.out::println); }}Copy the code
Sorted (Comparator) – Custom sort
package com.ysh.review01_Stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Stream; Public class StramTest02 {public static void main(String[] args) {Employee employee01=new Employee(" Yang "," ha ",19); Employee employee02=new Employee("yang","hui",49); Employee employee03=new Employee("yang","hui",79); Employee employee04=new Employee(" Yang "," hehehe ",79); Employee employee05=new Employee("yang","hui",39); Employee employee06=new Employee("yang","hui",29); List<Employee> list= Arrays.asList(employee01,employee02,employee03,employee04,employee05,employee06); Stream1 = list.stream(); // Create Stream<Employee> stream1 = list.stream(); / / to filter stream1 flow Stream < Employee > s = stream1. Filter ((e) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the filter -- -- -- -- -- -- -- -- -- -- -- -- "); Return LLDB etAge() >= 19; }); //s=s.skip(5); /* We can use Lambda expressions here, that is, s.sorted((o1, O2)->{// If the age is the same, If (o1.getage ()== O2.getage ()){return o1.getName().length()-o2.getName().length(); } return o1.getage () -o2.getage (); }) */ s=s.sorted(new Comparator<Employee>() {@override public int compare(Employee o1, Employee o2) { If (o1.getage ()== O2.getage ()){return o1.getName().length()-o2.getName().length(); } return o1.getage () -o2.getage (); }}); s.forEach((e-> System.out.println(e))); }}Copy the code
The map and flatMap methods in Stream:
- Each piece of data in the stream is treated as a parameter (interface) of the map method, and the parameters of the abstract method in the interface are specified, resulting in a result, and all the results are returned as a stream
- Each data in the stream is treated as a parameter, and the result must be a stream, which is eventually combined into a stream and returned
package com.ysh.review01_Stream; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class StreamTest04 { public static void main(String[] args) { Stream<String> stream=Stream.of("aaa","bbbb","ccccc"); {aaa}, {BBBB}, {CCCCC} are Stream<Character> streams. Stream<Character> = Stream<Character> = Stream<Character> = Stream<Character> //Stream<Stream<Character>> streamStream = stream.map((e) -> testCharacter(e)); Stream<Stream<Character>> streamStream = stream.map((e) -> { List<Character> list = new ArrayList<>(); for (Character c : e.toCharArray()) { list.add(c); } return list.stream(); }); streamStream.forEach((e)->{ e.forEach((e2)->{ System.out.println(e2); }); }); Stream<String> stm=Stream.of("aaa","bbbb","ccccc"); // The flatMap() method merges multiple Stream<Character> streams into a Stream<Character> Stream. stream1=stm.flatMap(StreamTest04::testCharacter); //streamStream.forEach(System.out::println); System.out.println("---------------"); stream1.forEach(System.out::println); } public static Stream<Character> testCharacter(String STR){List<Character> List =new ArrayList<>(); for (Character c:str.toCharArray()){ list.add(c); } Stream<Character> stream=list.stream(); return stream; }}Copy the code
Termination of operations
Find and match
- AllMatch: checks whether all elements match;
- AnyMatch: Checks whether at least one element is matched;
- NoneMatch: Checks if all elements are not matched;
- FindFirst: Returns the first element;
- FindAny: Returns any element in the current stream;
- Count: Returns the total number of elements in the stream;
- Max: returns the maximum value in the stream.
- Min: returns the minimum value in the stream;
Example code:
package com.ysh.review01_Stream; import java.util.Optional; import java.util.stream.Stream; Public class StreamTest06 {public static void main(String[] args) {// Get Stream<String> stm1=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); Boolean b1 = stm1.allmatch ((t) -> {return t.length() > 2; }); Stream<String> stm2=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); Boolean B2 =stm2. AnyMatch ((t) -> {return t.length() > 2; }); Stream<String> stm3=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); Boolean b3= stm3.nonematch ((t) -> {return t.length() > 2; }); Stream<String> stm4=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); // Get the first element in the stream Optional<String> first = stm4.findFirst(); / / output System. Out. Println (first. The get ()); Stream<String> stm5=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); // Return any element in the current stream Optional<String> any = stm5.findany (); System.out.println(any.get()); Stream<String> stm6=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); Long count = stm6.count(); System.out.println(count); Stream<String> stm7=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); // Return the maximum value of the stream, that is, the longest length, Optional<String> Max = stm7.max((s1, s2) -> {if (s1.length()==s2.length())){return s1.compareTo(s2); } return s1.length() - s2.length(); }); System.out.println(max.get()); Stream<String> stm8=Stream.of("aaaaaa","bbbbb","cccccc","dd","eee"); // Return the minimum value in the stream, that is, the shortest length, Optional<String> min = stm8.min((s1, s2) -> { if (s1.length() == s2.length()) { return s2.compareTo(s1); } return s1.length() - s2.length(); }); System.out.println(min.get()); System.out.println(b3); }}Copy the code
Collection:
Collect – Converts a Stream to another form and receives an implementation of the Collertor interface that summarizes the elements in the Stream
- List: Collect (Collectors. ToList ()).
- Set: Collect (Collectors. ToSet ()).
- Map: All elements in the flow are collected in the Map. If the same key occurs, an exception is thrown. Run.collect(Collectors.
- Several pieces of data can be obtained using the collect method. Collect (Collectors. Counting ())
- Collect (Collectors. AveragingInt (); collect(Collectors.
- Collect (Collectors. SummingDouble ()); collect(Collectors.
- If the collect method is used and the maximum value of a variable is obtained, run. Collect (Collectors. MaxBy ()).
Example code:
package com.ysh.review01_Stream.one; import java.util.*; import java.util.stream.Collectors; public class StreamTest07 { public static void main(String[] args) { Student stu1=new Student("1","hhhh",18); Student stu2=new Student("2","hhhhh",19); Student stu3=new Student("3","oooooo",19); Student stu4=new Student("4","aaaaa",19); List<Student> list = Arrays.asList(stu1,stu2,stu3,stu4); List<String> collect = list.stream().map((e) -> {return LLDB name (); }).collect(Collectors.toList()); System.out.println(collect); Set<String> set = list.stream().map((e) -> { return e.getName(); }).collect(Collectors.toSet()); System.out.println(collect); / / to the student's name and age into a collection, when the same key is throws a Java lang. An IllegalStateException: Duplicate Key exception Map<String, Integer> Map = list.stream().collect(Collectors. ToMap ((e) -> LLDB etName(), (e2) -> e2.getAge())); System.out.println(map); Long count2 = list.stream().collect(Collectors. Counting ()); System.out.println(count2); / / collect method is applied to estimate the average age of the students in all Double collect1 = list. The stream () collect (Collectors. AveragingDouble ((n) - > n.g etAge ())); System.out.println(collect1); Int agesum=list.stream().collect(Collectors. SummingInt ((e)-> LLDB ())); System.out.println(agesum); // Collect (Collectors. Max2 = list.stream().collect(Collectors. MaxBy ((a1, a2) -> a1.getAge() - a2.getAge())); System.out.println(max2.get()); } } class Student { private String id; private String name; private int age; public Student(){ } public Student(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String 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; } @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 && id.equals(student.id) && name.equals(student.name); } @Override public int hashCode() { return Objects.hash(id, name, age); } @Override public String toString() { return "Employee{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code
The last
Thank you for reading here, the article has any deficiencies also please correct, think the article is helpful to you remember to give me a thumbs-up!