A simple case
public class Demo12StreamFilter {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Zhang Wuji");
list.add("Zhou Zhiruo");
list.add("Zhao");
list.add("Zhang qiang");
list.add("Zhang Sanfeng");
list.stream()
.filter(s -> s.startsWith("Zhang"))
.filter(s -> s.length() == 3) .forEach(s -> System.out.println(s)); }}Copy the code
Reading the literal meaning of the code perfectly illustrates the semantics of the irrelevant logic approach: get stream, filter name, filter length 3, print one by one. Instead of iterating through the code using a linear loop or any other algorithm, what we really need to do is better represented in the code.
Overview of streaming ideas
Taken as a whole, the flow idea is similar to the “assembly line” on the factory floor.
When you need to operate on multiple elements (especially multi-step operations), for performance and convenience, you should first put together a “model” step scheme and then execute it.
This diagram shows multi-step operations such as filtering, mapping, skipping, and counting. It is a scheme for processing collection elements, and the scheme is a “functional model”. Each box in the diagram is a “flow” that can be converted from one flow model to another by calling the specified method. And the number 3 on the far right is the final result.
Get stream mode
Stream
is the most common new stream interface added to Java 8. (This is not a functional interface.)
Getting a stream is very simple. There are several common ways to get a stream:
- All of the
Collection
All sets can pass throughstream
The default method gets the stream; Stream
Static methods of the interfaceof
You can get the corresponding stream of the array.
Method 1: Get streams by Collection
First, the java.util.Collection interface adds the default method stream to fetch streams, so all of its implementation classes can fetch streams.
import java.util.*;
import java.util.stream.Stream;
1. Stream () 2.Stream (T... T) Add multiple data to Stream */
public class Demo13GetStream {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// ...
Stream<String> stream1 = list.stream();
Set<String> set = new HashSet<>();
// ...Stream<String> stream2 = set.stream(); }}Copy the code
Method 2: Get the stream from the array
If you are using arrays instead of collections or maps, the Stream interface provides the static method of, which is easy to use, since it is impossible to add default methods to array objects:
import java.util.stream.Stream;
public class Demo14GetStream {
public static void main(String[] args) {
String[] array = { "Zhang Wuji"."Zhang Cuishan"."Zhang Sanfeng"."Zhang Yi Yuan"}; Stream<String> stream = Stream.of(array); }}Copy the code
Note: The argument to the of method is actually a mutable argument, so arrays are supported.
Commonly used method
ForEach: One by one
Although the method name is forEach, it is different from the “for-each” nickname in the for loop
void forEach(Consumer<? super T> action);
Copy the code
This method receives a Consumer interface function that hands each stream element to the function for processing. Such as:
import java.util.stream.Stream;
public class Demo15StreamForEach {
public static void main(String[] args) {
Stream<String> stream = Stream.of("Big baby"."She"."Three dolls"."Four Eva"."Five Eva"."Six dolls"."Seven Eva"."Grandpa"."Snake essence".Scorpion essence);
//Stream
Stream = stream. of(" ", ""," ");
stream.forEach((String str)->{System.out.println(str);});
}
}
Copy the code
Here, lambda expression (String STR)->{system.out.println (STR); } is an example of a Consumer functional interface.
Filter: filter
A stream can be replaced with another subset stream using the Filter method. Method declaration:
Stream<T> filter(Predicate<? super T> predicate);
Copy the code
The interface accepts a Predicate function interface argument (which can be a Lambda) as a filter.
The basic use
The basic code for the filter method in Stream is as follows:
public class Demo16StreamFilter {
public static void main(String[] args) {
Stream<String> original = Stream.of("Zhang Wuji"."Zhang Sanfeng"."Zhou Zhiruo");
Stream<String> result = original.filter((String s) -> {return s.startsWith("Zhang");});
}
}
Copy the code
Here the criteria for filtering are specified by a Lambda expression: the last name must be Zhang.
Count: indicates the number of statistical elements
Just like the size method in the old Collection, the stream provides the count method to count the number of elements in it:
long count(a);
Copy the code
This method returns a long value representing the number of elements (no longer an int like the old collection). Basic use:
public class Demo17StreamCount {
public static void main(String[] args) {
Stream<String> original = Stream.of("Zhang Wuji"."Zhang Sanfeng"."Zhou Zhiruo");
Stream<String> result = original.filter(s -> s.startsWith("Zhang"));
System.out.println(result.count()); / / 2}}Copy the code
Limit: Limit the number (select the first X)
The limit method can intercept convection, taking only the first n. Method signature:
Stream<T> limit(long maxSize): Gets the first n elements of the Stream object and returns a new Stream objectCopy the code
The parameter is a long. If the current length of the collection is greater than the parameter, it is truncated. Otherwise, no operation is performed. Basic use:
import java.util.stream.Stream;
public class Demo18StreamLimit {
public static void main(String[] args) {
Stream<String> original = Stream.of("Zhang Wuji"."Zhang Sanfeng"."Zhou Zhiruo");
Stream<String> result = original.limit(2);
System.out.println(result.count()); / / 2}}Copy the code
Skip the first few
If you want to skip the first few elements, you can use the skip method to get a new truncated stream:
Stream<T> skip(long n): Skips the first n elements of the Stream object and returns a new Stream objectCopy the code
If the current length of the stream is greater than n, the first n are skipped; Otherwise you get an empty stream of length 0. Basic use:
import java.util.stream.Stream;
public class Demo19StreamSkip {
public static void main(String[] args) {
Stream<String> original = Stream.of("Zhang Wuji"."Zhang Sanfeng"."Zhou Zhiruo");
Stream<String> result = original.skip(2);
System.out.println(result.count()); / / 1}}Copy the code
Combination of concat:
If you have two streams that you want to merge into one, you can use the static method concat of the Stream interface:
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b): Merges two Stream objects a and B from the argument list into a new Stream objectCopy the code
Note: This is a static method, unlike the concat method in java.lang.String.
The basic usage code for this method is as follows:
import java.util.stream.Stream;
public class Demo20StreamConcat {
public static void main(String[] args) {
Stream<String> streamA = Stream.of("Zhang Wuji");
Stream<String> streamB = Stream.of("Zhang Cuishan"); Stream<String> result = Stream.concat(streamA, streamB); }}Copy the code
Collect: Convert to a collection
Convert a Stream object into a collection object using the Stream interface method collect:
public static void main(String[] args) {
Stream stream = Stream.of("aa"."bb"."cc"."dd"."ee"."ee");
Set<String> list = ( Set<String> )stream.collect(Collectors.toSet());
for(String s :list){ System.out.println(s); }}Copy the code