I'm still a beginner in programming, and I'm going to write a series that spells out descriptions that I thought I could use or use when manufacturing Java in a ** memorandum **. It's just a memorandum, so I plan to use it for myself. This time, which is the first post, it will be like *** Let's write from the very basics and remember the transcendental basics.
First of all, a description that replaces a common For statement with a Stream Suppose you have a list with the following numbers.
List<Integer> iList = Arrays.asList(1,4,5,7,14,15,77,98,100,103);
I want to output only even numbers from here. Below is the code in an ordinary extended For statement that outputs only even numbers.
for (Integer i : iList) {
if (i % 2 == 0) {
System.out.println(i);
}
}
Output result
4
14
98
100
If you replace the above with Stream ...
iList.stream().filter(i -> i % 2 == 0).forEach(i -> System.out.println(i));
Output result
4
14
98
100
Here is a rough description of what you are doing with Stream first
iList.stream()
So, get the stream
.filter(i -> i % 2 == 0)
Perform an operation called intermediate operation with
.forEach(i -> System.out.println(i));
The final operation called the termination operation is performed at.
This flow of "intermediate operation" ⇒ "termination operation" is the basis of Stream, so If you remember this much, it's easy to google even if you forget a little about how to write.
So, as you can see, the above For statement and Stream have the same processing result, but in detail, it seems that what they are actually doing is different.
*** For the familiar For statement *** Loop iList only for the element statement of iList, and if the element has a value divisible by 2, output it, otherwise it will not output and go to the next element! Processing such as.
*** For Stream *** Specify the filtering condition with the "filter method" used for the intermediate operation, Extract the elements filtered by the "for Each method" one by one and execute them! Processing such as (output in this case).
There are various types of intermediate operations and termination operations, and by combining them, you can perform various processing you want to write. I often use the intermediate operation "map method" (conversion) and the termination operation "Collect" (list generation).
Next, I will write what kind of operation method is used at what time.
Recommended Posts