In Java8, there is the concept of stream flow. I personally think that the use of streams can help us better iterate over the collection of data.
Let's take a look at the code for the normal for loop and stream stream.
public static void Main (string[] args) { //Remove even list<integer> List = arrays.aslist (1,2,3,4); 1.for loop list<integer> newList1 = new arraylist<> (); For (integer integer:list) { if (integer% 2 = = 0) { newlist1.add (integer);} } System.out.println (newList1); 2.stream stream list<integer> newList2 = List.stream (). filter (x, x 2 = = 0). Collect (Collectors.tolist ()); C12/>system.out.println (NEWLIST2); }
Output Result:
[2, 4][2, 4]
As you can see, the use of stream streams can sometimes simplify the accountability of our code, and with lambda expressions, you can make your code easier to understand.
Here's a brief introduction to the use of stream streams in Java:
1. Create Stream stream
List collection Creation Create: Call list's Stream method, such as List.stream ()
The array is created by passing in the array via Arrays.stream (), such as: Arrays.stream (new integer[]{1,2})
Note: Stream streams are created and can only be used once, and need to be created again if you want to cycle again!
2. Introduction of common methods:
The flow method is divided into intermediate operations and terminal operations, as the name implies, intermediate operation refers to the call method after the generation of a new stream, you can continue to perform operations, and terminal operations is the end of the use of the stream.
Intermediate Operation:
1.filter filter out non-conforming data
2.limit takes only the first X data
3.skip Skip (delete) x data
4.distinct to duplicate data
5.sorted sorting
6.map to data reorganization, generate new data stream (how to remove user age from user collection stream as new stream)
Terminal operation:
1.count Statistical Data Quantity
2.forEach each data in the stream executes the incoming method
3.anyMatch at least one match, return bool
4.allMatch matches all, returns bool
5.collect can pass in a common method in the collection, for example: Collector.tolist () flows back to the collection, Collector.groupingby () groups the data in the stream
6.reduce perform a return operation, such as summation, etc.
Let's start with a simple introduction to stream streaming in Java, thank you.
Simple use of stream in Java