This is the third day of my participation in the August Text Challenge.More challenges in August
preface
Stream is the key abstraction for dealing with collections in Java8. It can specify what you want to do with collections, and can perform very complex operations like finding, filtering, and mapping data. Manipulating collection data using the Stream API is similar to database queries executed using SQL. You can also use the Stream API to perform operations in parallel. In short, the Stream API provides an efficient and easy-to-use way to process data. Let programmers write efficient, clean, concise code.
What is a Stream?
A Stream is a queue of elements from a data source and supports aggregation operations. Streams are transmitted in a pipe and can be processed on the nodes of the pipe, such as filtering, sorting, aggregation, and so on. Stream consists of elements, data sources, aggregation operations, internal iteration, Pipelining, and more.
- Element: Objects of a specific type
- Data source: source of a stream, collection of elements, array, etc.
- Aggregate operations: Operations similar to SQL statements, such as filter, Map, reduce, find, match, sorted, etc.
- Internal iteration: Iterates internally within a stream, as opposed to for external processing.
- Pipelining: All intermediate operations return the flow object itself.
Basic Stream operations
Initialize two sets of data
List<String> stringList = Arrays.asList("juejin", "zijie", "toutiao", "feidian", "join","", "juelimanman"); List<Integer> integerList = Arrays. AsList (0, 1, 2, 3, 4, 5, 6, 7,8, 9, 10,11,12);Copy the code
The Stream to create
stream()
Create a serial stream using stream().
Stream<String> stream = stringList.stream();
Copy the code
parallelStream()
The parallelStream() method creates parallel streams
Stream<String> stringStream = stringList.parallelStream();
Copy the code
Arrays.stream()
Use the stream() method from Arrays
Stream<String> stream1 = Arrays.stream(new String[10]);
Copy the code
Stream.of
Stream.of creates a Stream, which is a finite Stream
Stream<String> streamOf = Stream.of("juejin", "zijie", "toutiao", "feidian", "join","", "juelimanman");
Copy the code
Stream.iterate
Stream. Iterate Creates a Stream, which creates an ordered infinite data Stream
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(5);
Copy the code
Stream.generate
Stream. Generate Creates a Stream, creating an unlimited data Stream
Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
Copy the code
reader.lines
Turn each line into a stream using the bufferedreader.lines () method
Stream<String> lineStream = reader.lines();
Copy the code
The Stream operation
forEach
ForEach iterates through each data in the stream, outputting all elements
stringList.forEach(System.out::println);
Copy the code
map
The map method is used to map each element to the corresponding result
stringList.stream().map(i->i.equals("juejin"));
Copy the code
flatMap
FlatMap: Replace every value in the stream with another stream, and then join all streams into one.
stream.flatMap(String::toUpperCase).collect(Collectors.toList());
Copy the code
filter
The filter method is used to filter out elements by setting criteria, filtering certain elements in a stream
stringList.stream().filter(i->i.equals("juejin"));
Copy the code
peek
Like a map, you can get every element in the flow. But the map receives a Function expression that returns a value; Peek receives the Consumer expression and returns no value.
stream.peek(s -> s.equals("juejin"));
Copy the code
limit
The limit(n) method is used to get a specified number of streams. For example, limit(n) : obtains n elements
integerList.stream().limit(3);
Copy the code
skip
Skip (n) : Skip n elements, together with limit(n) can achieve paging
integerList.stream().skip(5).limit(3);
Copy the code
distinct
Distinct: Removes duplicate elements by hashCode() and equals() of elements in the stream
integerList.stream().distinct().collect(Collectors.toList());
Copy the code
sorted
Sorted The sorted method is used to sort by convection, naturally.
integerList.stream().sorted();
Copy the code
sorted(Comparator com)
Sorted (Comparator com) : Custom sort, custom Comparator sorter
integerList.stream().sorted(Comparator.comparing(Integer::intValue));
Copy the code
parallel
ParallelStream is an alternative to stream parallel processing.
integerList.parallelStream().sorted();
Copy the code
Collectors
The Collectors class implements many reduction operations, such as replacing flows with collections and aggregation elements.
stringList.stream().filter(s -> s.equals("juejin")).collect(Collectors.toList());
Copy the code
count
A collector of count statistics is also useful, and termination operations are used at the end of a stream.
integerList.stream().count();
Copy the code
allMatch
AllMatch: Receives a function that returns true only if every element in the stream matches this assertion, false otherwise, terminating the stream, used at the end of the stream
integerList.stream().allMatch(integer -> integer>0);
Copy the code
noneMatch
NoneMatch: Receives a function that returns true if every element in the stream does not match this assertion, false otherwise, and terminates the stream, used at the end of the stream.
integerList.stream().noneMatch(integer -> integer>100);
Copy the code
anyMatch
AnyMatch: Receives a function that returns true as long as one element of the stream satisfies this assertion, false otherwise, terminating the stream, used at the end of the stream.
integerList.stream().anyMatch(integer -> integer>2);
Copy the code
findFirst
FindFirst: Returns the first element in the stream, the termination operation of the stream, used at the end of the stream.
stringList.stream().findFirst();
Copy the code
findAny
FindAny: Returns any element in the stream, terminates the stream, and is used at the end of the stream.
stringList.stream().findAny();
Copy the code
max
Max: returns the maximum number of elements in the stream, the termination operation of the stream, used at the end of the stream.
userList.stream().max(Comparator.comparingInt(user::score));
Copy the code
min
Min: returns the minimum value of the element in the stream, the termination operation of the stream, used at the end of the stream.
userList.stream().min(Comparator.comparingInt(user::score));
Copy the code
collect
Collect: Receive an instance of Collector to collect elements from the stream into another data structure.
integerList.stream().filter(u->user.getScore>60).collect(Collectors.toList());
Copy the code
conclusion
The Stream API provides an efficient and easy-to-use way to process data. Let programmers write efficient, clean, concise code. Stream uses complex expressions to handle data logic, but you can learn about these methods first, and when you use them in your project, you can learn more about them and do more complex combinations.
About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.
Well, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.