In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains how to use stream Stream in Java functional programming. The explanation in this article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn how to use stream stream in Java functional programming.
List words = Arrays.asList ("hello", "world"); List chars = words.stream () .flatMap (word-> Stream.of (word.split (") .flat (Collectors.toList ())
The new features in Jdk8 are designed to help programmers write better code, and improvements to the core class libraries are a key part of it. The improvements to the core class library mainly include the API of the collection class and the newly introduced Stream. Flow enables programmers to operate on collections at a higher level of abstraction.
1. What is Stream?
A Stream is a queue formed by specific types of objects and supports aggregation operations. Stream in Java does not store elements, but is calculated on demand. The sources of streams can be collections, arrays, I _ channel, generator generator, and so on. Aggregate operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, and so on. Unlike previous Collection operations, Stream operations have two basic characteristics: Pipelining intermediate operations return the stream object itself. Such multiple operations can be concatenated into a single pipe, like streaming style (fluent style). Doing so optimizes operations, such as delayed execution (laziness) and short-circuiting.
In Java 8, the collection interface has two ways to generate the flow:
Stream () − creates a serial flow for the collection.
ParallelStream () − creates a parallel flow for the collection.
List list = Arrays.asList ("a", "b", "c", "d", null); List filtered = list.stream (). Filter (e-> Objects.nonNull (e)). Filter (Collectors.toList ()); long count = list.parallelStream (). Filter (e-> Objects.nonNull (e)). Count (); 2. Internal iteration
When using a collection, Java programmers iterate over the collection in a general pattern, processing each element and returning the result during the iteration. Usually the code looks like this:
List list = Arrays.asList (1,2,3,4,5); int sum = 0; Iterator iterator = list.iterator (); while (iterator.hasNext ()) {sum + = iterator.next ();} System.out.println (sum)
There is nothing wrong with this code itself, but it is a bit troublesome to write. According to the principle behind it, it is actually a syntax sugar that encapsulates iterations. First, call the iterator method to generate a new Iterator object and then control the whole iteration process. This is the external iteration.
The problem with external iterations, however, is that, first of all, it is difficult to abstract the complex operations mentioned later, and it is essentially a serialization operation. In general, using for loops confuses behaviors with methods. Another method is internal iteration, which uses the stream () method like calling iterator (), which instead of returning an Iterator object that controls the iteration, returns the corresponding interface in the internal iteration: Stream. Examples are as follows:
List list = Arrays.asList (1,2,3,4,5,6,7,8,9,10); Integer sum = list.stream (). Filter (e-> e > 5). Reduce (0, Integer::sum); System.out.println (sum); 3. Realization mechanism
Usually when calling a method in Java, the computer will immediately perform the operation: for example, System.out.println ("hello world!") A message is output on the terminal. Some of the methods in Stream are slightly different. Although they are ordinary Java methods, the Stream object returned is not a new collection, but a recipe for creating a new collection.
List.stream () .filter (e-> e > 5)
The above code does not do any practical work, filter just depicts the Stream but does not generate a new set, like filter only describes the Stream, and ultimately does not produce a new set of methods lazy evaluation method, and such as sum () ultimately produces a value from the Stream method is called early evaluation method. If you add an output statement to the filter method, you will see the difference more clearly.
List list = Arrays.asList (1,2,3,4,5,6,7,8,9,10); list.stream () .filter (e-> {System.out.println (e); return e > 5;})
If you add an early evaluation method to the above statement, you can see that the elements in the collection are printed.
List list = Arrays.asList (1,2,3,4,5,6,7,8,9,10); list.stream () .filter (e-> {System.out.println (e); return e > 5;}) .findFirst ()
It is easy to determine whether an operation evaluates lazily or early, as long as the return value is Stream. The ideal way to use these operations is to form a lazy evaluation chain and finally return the desired result with an early evaluation operation, which is reasonable. So why distinguish between lazy evaluation and early evaluation? The reason is simple: it only takes one iteration to get all the results. For example, the above code only needs to find the first number greater than 5 without comparing all the collection elements.
4. Common stream operations
In order to better learn Stream, let's next learn some common stream operations.
Filter
If you need to clean illegal elements while traversing collection elements, you can use the filter method, which we have used in the above discussion. Filter takes a function as an argument, which uses a lambda expression to indicate that if the cleaned element meets the expectation, it returns true. In fact, if you look at the source code, you will find that this lambda expression is the Predicate function we talked about earlier.
Collect
This method is a List generated by Stream, which is an early evaluation operation. Jdk8 draws on a lot of Scala design ideas. Stream's of method can be used to generate a new Stream. Let's take a look at the following example.
List list = Stream.of ("a", "b", "c", "d", "e") .duration (Collectors.toList ())
Map
The map function is used to convert one type to another, and the argument is also a lambda expression corresponding to the Function function we talked about earlier. Because map is a lazy evaluation method, let's look at an example with the previous collect.
List list = Stream.of ("a", "b", "c") .map (e-> e.toUpperCase ()) .map (Collectors.toList ()); System.out.println (list)
FlatMap
Similar to map, except that each element is transformed into a Stream object, which eventually concatenates multiple Stream into a Stream.
List words = Arrays.asList ("hello", "world"); List chars = words.stream () .flatMap (word-> Stream.of (word.split (") .flat (Collectors.toList ())
We can get the output result of the above code: [h, e, l, l, o, w, o, r, l, d]. If we replace flatMap with map, we will find that we have got a List. If you are interested, you can try it.
Max and min
Unlike the functions mentioned earlier, these two methods require that the argument be a comparator Comparator
Integer min = Stream.of. Min (Integer::compare). Get (); System.out.println (min); Integer max = Stream.of. Max (Integer::compare). Get (); System.out.println (max)
Reduce
This function can generate a value from a set of values, and the sum, max, and min used in the above example are essentially reduce operations. The summation result of Stream accumulates the elements in Stream to accumulator at each step, and when traversing to the last element in Stream, the value of accumulator is the sum of all elements. Let's look at the following example
Integer sum = Stream.of (1,2,3,4,5). Reduce (0, (acc, e)-> acc + e); System.out.println (sum)
This code is easy to understand if you are familiar with scala. Acc is used as an accumulator to store intermediate calculation results, and the whole lambda function is essentially the BinaryOperator we talked about earlier.
Thank you for reading, the above is the content of "how to use stream Stream in Java functional programming". After the study of this article, I believe you have a deeper understanding of how to use stream Stream in Java functional programming, 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.