In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn Java8 Stream from scratch". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to learn Java8 Stream from scratch.
Why do you need to introduce a stream?
In our normal development, we will go to List, Map and other collections API almost every day. If you ask Java what API is most used, I think it should also be a collection. For example: if I have a collection of List, in which there are elements 1, 7, 3, 8, 2, 4, 9, I need to find out the elements that are greater than 5, and the specific implementation code:
Public List getGt5Data () {List data = Arrays.asList (1,7,3,8,2,4,9); List result = new ArrayList (); for (Integer num: data) {if (num > 5) {result.add (num);}} return result;}
This implementation makes us feel that the operation of the collection is not perfect. If it is a database, we only need to add a condition greater than 5 after where to get the results we want. Why does the collection of Java not have this kind of API? Secondly, if we encounter a large set to deal with, in order to improve performance, we may need to use multithreading to process, but the complexity of writing parallel programs has increased a lot.
Based on the above problems, all Java8 launched Stream.
Introduction to Stream
What are the characteristics of Stream:
Sequence of elements: elements can be accessed just like collections. Collections are about data, while streams are about operations, such as filter and map.
Source: the stream also needs another source of data, in the same order as it was generated.
Operation of data: stream supports operations similar to database, supports sequential or parallel processing of data; the above example is more concise to implement with stream
Public List getGt5Data () {return Stream.of (1,7,3,8,2,4,9) .filter (num-> num > 5) .filter (toList ());}
Pipelined operation: many streaming methods themselves return a stream, which connects multiple operations to form a pipelined operation.
Internal iterations: unlike previous iterations, streams use internal iterations in which users only need to focus on data processing
It can only be traversed once: after traversing, our stream has been consumed. If we iterate again, an exception will be thrown.
Use Stream
Stream in Java8 defines many methods, which can be basically divided into two categories: intermediate operations and terminal operations. To use a stream, you generally need three operations:
Define a data source
Define intermediate operations to form a pipeline
Define terminal operation, execute pipeline, and generate calculation results.
Build flow
Build a flow using the Stream.of method
Stream.of ("silently", "9527", "silently9527.cn") .forEach (System.out::println)
Use arrays to build a stream
Int [] nums = {3,5,2,7,8,9}; Arrays.stream (nums) .sorted () .forEach (System.out::println)
Build a stream from a file you can easily build a stream object using the java.nio.file.Files.lines method
Files.lines (Paths.get ("/ Users/huaan9527/Desktop/data.txt")) .forEach (System.out::println); intermediate operation
The intermediate operation returns another stream, which allows multiple operations to be connected to form a pipelined operation, which is not actually performed as long as the terminal operation is not triggered.
Filter
This operation accepts a function that returns boolean, and the element that returns false will be excluded.
Example: if we have 100 customers, we need to screen out customers who are older than 20 years old.
List matchCustomers = allCustomers.stream () .filter (customer-> customer.getAge () > 20) .filter (toList ()); distinct
This action will exclude duplicate elements
List data = Stream.of (1, 7, 3, 8, 2, 4, 9, 7, 9) .filter (num-> num > 5) .filter (toList ()); limit
This method restricts the flow to return only a specified number of elements
List data = Stream.of (1, 7, 3, 8, 2, 4, 9, 7, 9) .filter (num-> num > 5) .limit (2) .limits (toList ()); skip
Throw away the specified number of elements; use it with limit to achieve the effect of turning pages.
List data = Stream.of (1, 7, 3, 8, 2, 4, 9, 7, 9) .filter (num-> num > 5) .skip (1) .limit (2) .limits (toList ()); map
This method provides a function to which each element in the flow is applied, and the result returned will form a new type of flow to continue the subsequent operation. For example: if we have 100 customers, we need to screen out customers over the age of 20 and print out their names.
AllCustomers.stream () .filter (customer-> customer.getAge () > 20) .map (Customer::getName) .forEach (System.out::println)
The type of stream before calling map is Stream, and the type after executing map is Stream
FlatMap
If we need to print out each character in the customer's name, the code is as follows:
List allCustomers = Arrays.asList (new Customer ("silently9527", 30)); allCustomers.stream () .filter (customer-> customer.getAge () > 20) .map (customer-> customer.getName () .split (")) .forEach (System.out::println)
If you execute this result, you will find that it does not achieve the desired result, the printed result.
[Ljava.lang.String;@38cccef
This is because the stream type returned after calling map is Stream, and the input of all forEach is String []. In this case, we need to use flatMap to convert each element in String [] into a stream, and then concatenate all the streams into a stream. The modified code is as follows
List allCustomers = Arrays.asList (new Customer ("silently9527", 30); allCustomers.stream () .filter (customer-> customer.getAge () > 20) .map (customer-> customer.getName () .split (")) .flatMap (Arrays::stream) .forEach (System.out::println)
Execution result:
Sorted
Sort all elements
List numbers = Arrays.asList (1,7,3,8,2,4,9); numbers.stream () .sorted (Integer::compareTo) .forEach (System.out::println); terminal operation
The terminal operation performs all intermediate operations to generate the result of execution, and the result of execution is no longer a stream.
AnyMatch
True is returned if an element in the stream satisfies the condition
If (allCustomers.stream () .anyMatch (customer-> "silently9527" .equals (customer.getName () {System.out.println ("user silently9527 exists");} allMatch
Make sure that all elements in the stream are satisfied
If (allCustomers.stream () .allMatch (customer-> customer.getAge () > 20)) {System.out.println ("all users are older than 20");} noneMatch
In contrast to the allMatch operation, ensure that all elements in the flow are not satisfied
If (allCustomers.stream () .noneMatch (customer-> customer.getAge ())
< 20)) { System.out.println("所有用户年龄都大于20");}findAny 返回流中的任意一个元素,比如返回大于20岁的任意一个客户 Optional optional = allCustomers.stream() .filter(customer ->Customer.getAge () > 20) .findAny (); findFirst
The first element in the return stream
Optional optional = allCustomers.stream () .filter (customer-> customer.getAge () > 20) .findFirst (); reduce
Accept two parameters: an initial value, a BinaryOperator accumulator merges two elements into a new value, for example, we accumulate a number list
List numbers = Arrays.asList (1,7,3,8,2,4,9); Integer sum = numbers.stream () .reduce (0, (a, b)-> a + b)
The above code can be abbreviated.
Integer reduce = numbers.stream () .reduce (0, Integer::sum)
Find out the maximum and minimum values in the stream, min, max
Numbers.stream (). Reduce (Integer::max) numbers.stream (). Reduce (Integer::min) count
Count the number of elements in the flow
Numbers.stream (). Count () data collector collect
Many collectors have been predefined in Java8, and we can use them directly. All collectors are defined in Collectors. Basically, these methods can be divided into three categories:
Reduce and summarize elements into one value
Grouping
Zoning
Reduction and summary
First, let's take a look at how to achieve the maximum and minimum values by using the collector.
Find the oldest and youngest customers
Optional minAgeCustomer = allCustomers.stream () .collect (minBy (Comparator.comparing (Customer::getAge); Optional maxAgeCustomer = allCustomers.stream () .collect (maxBy (Comparator.comparing (Customer::getAge)
Get the average age.
Double avgAge = allCustomers.stream () .collect (averagingInt (Customer::getAge))
Make a string concatenation
Concatenate the names of customer owners into a string separated by commas
AllCustomers.stream () .map (Customer::getName) .grouping (joining (","))
In the operation of the database, we can easily implement data grouping through one or more attributes, and then let's take a look at how Java8 implements this function.
Group according to the age of the customer
Map groupByAge = allCustomers.stream () .collect (groupingBy (Customer::getAge))
The key of Map is the value age of the grouping, and List is the user of the same age.
We need to group users by region and by age.
Map groups = allCustomers.stream () .cake (groupingBy (Customer::getArea, groupingBy (Customer::getAge)
In contrast to ordinary grouping, the second parameter here is another groupingBy;. Theoretically, we can extend it to n-tier grouping in this way.
Count the quantity after grouping.
Map groupByCounting = allCustomers.stream () .cake (groupingBy (Customer::getArea, counting ()
Find out the oldest user after grouping according to the user's region
Map optionalMap = allCustomers.stream () .cake (groupingBy (Customer::getArea, maxBy (Comparator.comparing (Customer::getAge)
At this time, the value in the returned Map is wrapped by Optional. If we need to remove Optional, we can use collectingAndThen
Map customerMap = allCustomers.stream () .cake (groupingBy (Customer::getArea, collectingAndThen (maxBy (Comparator.comparing (Customer::getAge)), Optional::get) Thank you for your reading, the above is the content of "how to learn Java8 Stream from scratch". After the study of this article, I believe you have a deeper understanding of how to learn Java8 Stream from scratch, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.