Foreword
Only the head can become strong.
Text has been included to my GitHub repository, welcome Star: https://github.com/ZhongFuCheng3y/3y
Previous to explain the use of Lambda expressions " recently learned the basics of Lambda expressions ," I have not seen the students can go to read the Ha ~
I believe there are a lot of students want to know: Lambda expressions which scene will be used more than at work? Take sides with Lambda, use Stream flow will be more
Most people first look at the code Stream flow, will not read a bit (it looks as if the code is not written as Java.), I hope this article will take you into the door
First, the experience Stream flow
Everyone in the self-study, most will learn to have a program: 算出从数组元素的和
when we are how to write? In general is this:
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
int sum = 0;
for (int i : nums) {
sum += i;
}
System.out.println("结果为:" + sum);
}
If we use Stream flow, then it can be:
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
int sum2 = IntStream.of(nums).sum();
System.out.println("结果为:" + sum2);
}
From code quantity on apparent, Stream manner stream will be less.
I understand the Stream flow programming is this: some scenes will be frequently used operations (sum / de-emphasis / filter .... etc.), API has been packaged good to you, you do not write, I'll give you tune API provides just fine .
1.1 supports concurrent
Back to our most primitive code:
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
int sum = 0;
for (int i : nums) {
sum += i;
}
System.out.println("结果为:" + sum);
}
If we want for
the inner loop of the support concurrent, then obviously not very good to write. But the use of Stream flow way, calling a method can support concurrent (parallel):
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
int sum2 = IntStream.of(nums).parallel().sum();
System.out.println("结果为:" + sum2);
}
Advantages: API tone is certainly less than the amount of code you wrote it myself.
Cons: not very convenient debugging
Why use Stream flow in my opinion is more than two reasons:
- Concurrent convenient
- Less code (called directly API)
Second, how to use Stream flow?
Use Stream flow is divided into three steps:
- Creating Stream flow
- By performing the intermediate operation Stream stream objects
- The final action, the result obtained
2.1 creates a stream
We create a stream most commonly used is from the collection to create flow
/**
* 返回的都是流对象
* @param args
*/
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 从集合创建
Stream<String> stream = list.stream();
Stream<String> stream1 = list.parallelStream();
// 从数组创建
IntStream stream2 = Arrays.stream(new int[]{2, 3, 5});
// 创建数字流
IntStream intStream = IntStream.of(1, 2, 3);
// 使用random创建
IntStream limit = new Random().ints().limit(10);
}
2.2 performing the intermediate operation
How to understand the middle of the operation? Meaning is this: In the above we have been able to create Stream, we are on the Stream operation, Stream operation returns to complete or return the Stream, we call this operation as an intermediate operation.
For example, we now have a string my name is 007
, as follows:
String str = "my name is 007";
Stream.of(str.split(" ")).filter(s -> s.length() > 2)
.map(s -> s.length()).forEach(System.out::println);
break down:
1, the stream object to create an array of strings:
Stream<String> split = Stream.of(str.split(" "));
2, performed by the stream object API intermediate operation (filter), or the return stream object:
Stream<String> filterStream = split.filter(s -> s.length() > 2);
3, then performing the intermediate operation (Map) by a stream object, stream object is returned:
Stream<Integer> integerStream = filterStream.map(s -> s.length());
Since the middle of the operation are returned stream object , so we can be chained calls .
Note: The operation on the Stream will not be executed immediately, users really need only wait until the results will be performed ( lazy evaluation ).
For example, peek()
an intermediate operation returns Stream stream objects, as long as it is not a final operation performed, the Stream will not be implemented.
String str = "my name is 007";
Stream.of(str.split(" ")).peek(System.out::println); // 不会有信息打印
2.3 performing final operations
The final operation is no longer returned Stream object, called the final method of operation, Stream will be performed . Or in the example above, for example:
String str = "my name is 007";
Stream.of(str.split(" ")).peek(System.out::println).forEach(System.out::println)
This time we joined the final operation, so this Stream flows will be executed, because the intermediate operations and final operations are executed print, it will see two print:
As for the middle of the operation and how to distinguish between final operation, we have to return value to see on the line. Stream intermediate operation returns the object instance, the operation returns to the final instance of an object is not a Stream:
At last
This article preliminary understanding with everyone together at Stream flow, as intermediate operations, API to explain the operation of the final I do not write (there are many online tutorials)
The reason for using the Stream I think there are two:
- JDK libraries provide existing API, the code to write simple optimization
- Convenient concurrency. We can remember a conclusion: in multicore case, you can use parallel Stream API to play a multi-core advantage. In the case of single-core, write our own
for
performance much worse than Stream API
References:
Willing output of dry cargo of Java technology public number: Java3y . A public number more than 200 original articles technical articles, massive video resources, beautiful mind map, attention can get!
I think the article is well written, points praise !