Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the common method of Java8 Stream flow

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of what the common methods of Java8 Stream flow are, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on common methods of Java8 Stream flow. Let's take a look at it.

I. Overview

Stream is a key abstract concept of dealing with collections in Java8. It can specify the operations you want to do on the collection, and can perform very complex operations such as finding, filtering, and mapping data. Using Stream API to manipulate collection data is similar to a database query performed using SQL. You can also use Stream API to perform operations in parallel.

In short, Stream API provides an efficient and easy-to-use way to process data.

Features:

It is not a data structure and the data is not saved.

The original data source is not modified, it saves the data after the operation to another object. (reservation: after all, the peek method can modify the elements in the flow)

Lazy evaluation, flow in the intermediate process, only the operation is recorded, and will not be performed immediately, need to wait until the termination operation will be carried out the actual calculation.

II. Classification

Stateless: means that the processing of an element is not affected by the previous element

Stateful: means that the operation can not continue until you have all the elements.

Non-short-circuit operation: means that all elements must be processed to get the final result

Short circuit operation: you can get the final result when you encounter some qualified elements, such as A | | B, as long as An is true, there is no need to judge the result of B.

Third, specific usage 1. Common methods for creating streams

1.1 use the stream () and parallelStream () methods under Collection

List list = new ArrayList (); Stream stream = list.stream (); / / get a sequential stream Stream parallelStream = list.parallelStream (); / / get a parallel stream

1.2 convert an array into a stream using the stream () method in Arrays

Integer [] nums = new Integer [10]; Stream stream = Arrays.stream (nums)

1.3 use static methods in Stream: of (), iterate (), generate ()

Stream stream = Stream.of; Stream stream2 = Stream.iterate (0, (x)-> x + 2) .limit (6); stream2.forEach (System.out::println); / / 02468 10Stream stream3 = Stream.generate (Math::random) .limit (2); stream3.forEach (System.out::println)

1.4 convert each line of content into a stream using the BufferedReader.lines () method

BufferedReader reader = new BufferedReader (new FileReader ("F:\\ test_stream.txt"); Stream lineStream = reader.lines (); lineStream.forEach (System.out::println)

1.5 use the Pattern.splitAsStream () method to separate strings into streams

Pattern pattern = Pattern.compile (","); Stream stringStream = pattern.splitAsStream ("a _ r _ b _ r c _ r d"); stringStream.forEach (System.out::println); 2. Intermediate operation of a stream

2.1 screening and slicing

Filter: filter some elements in the stream

Limit (n): get n elements

Skip (n): skip n elements and work with limit (n) to achieve paging

Distinct: removes duplicate elements through hashCode () and equals () of elements in the flow

Stream stream = Stream.of (6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14); Stream newStream = stream.filter (s-> s > 5) / / 6 6 7 9 8 10 12 14 14.distinct () / 6 7 9 8 10 12 14.skip (2) / 9 8 10 12 14.limit (2); / 9 8newStream.forEach (System.out::println)

2.2 Mapping

Map: takes a function as an argument, which is applied to each element and mapped to a new element.

FlatMap: takes a function as an argument, replaces each value in the stream with another stream, and then connects all streams into one stream.

List list = Arrays.asList; / / convert each element into a new element without a comma, Stream S1 = list.stream (). Map (s-> s.replaceAll (",", ")); s1.forEach (System.out::println); / / abc 123Stream S3 = list.stream (). FlatMap (s-> {/ / convert each element into a streamString [] split = s.split (", ") Stream S2 = Arrays.stream (split); return S2;}); s3.forEach (System.out::println); / / a b c 1 2 3

2.3 sort

Sorted (): natural sorting. Elements in the stream need to implement Comparable interface.

Sorted (Comparator com): custom sorting, custom Comparator sorter

List list = Arrays.asList ("aa", "ff", "dd"); / / the String class itself has implemented the Compareable interface list.stream (). Sorted (). ForEach (System.out::println); / / aa dd ffStudent S1 = new Student ("aa", 10); Student S2 = new Student ("bb", 20); Student S3 = new Student ("aa", 30); Student S4 = new Student ("dd", 40); List studentList = Arrays.asList (S1, S2, S3, S4) / / Custom sorting: studentList.stream (). Sorted ((o1, O2)-> {if (o1.getName (). Equals (o2.getName () {return o1.getAge ()-o2.getAge ();} else {return o1.getName (). CompareTo (o2.getName ());}}) .forEach (System.out::println)

2.4 consumption

Peek: like map, you can get every element in the stream. But map receives an Function expression with a return value, while peek receives an Consumer expression with no return value.

Student S1 = new Student ("aa", 10); Student S2 = new Student ("bb", 20); List studentList = Arrays.asList (S1, S2); studentList.stream (). Peek (o-> o.setAge (100)) .forEach (System.out::println); / / result: Student {name='aa', age=100} Student {name='bb', age=100} 3. Termination of the stream

3.1 matching and aggregation operations

AllMatch: receives a Predicate function that returns true when every element in the stream meets the assertion, otherwise it returns false

NoneMatch: receives a Predicate function that returns true when every element in the stream does not conform to the assertion, otherwise returns false

AnyMatch: receives a Predicate function that returns true as long as an element in the stream satisfies the assertion, otherwise it returns false

FindFirst: the first element in the return stream

FindAny: any element in the return stream

Count: returns the total number of elements in the stream

Max: returns the maximum value of the element in the stream

Min: returns the minimum value of an element in the stream

List list = Arrays.asList (1,2,3,4,5); boolean allMatch = list.stream (). AllMatch (e-> e > 10); / / falseboolean noneMatch = list.stream (). NoneMatch (e-> e > 10); / / trueboolean anyMatch = list.stream (). AnyMatch (e-> e > 4); / / trueInteger findFirst = list.stream (). FindFirst (). Get (); / / 1Integer findAny = list.stream (). FindAny (). Get () / / 1long count = list.stream () .count (); / / 5Integer max = list.stream () .max (Integer::compareTo) .get (); / / 5Integer min = list.stream () .min (Integer::compareTo) .get (); / / 1

3.2 stipulate operation

Optional reduce (BinaryOperator accumulator): when executed for the first time, the first parameter of the accumulator function is the first element in the flow, and the second parameter is the second element of the element in the flow; the second execution, the first parameter is the result of the first function execution, the second parameter is the third element in the flow, and so on.

T reduce (T identity, BinaryOperator accumulator): the process is the same as above, except that the first argument to the accumulator function is identity, and the second argument is the first element in the flow.

U reduce (U identity,BiFunction accumulator,BinaryOperator combiner): in serial flow (stream), this method is the same as the second method, that is, the third parameter, combiner, does not work. In parallel flow (parallelStream), we know that the flow is executed by multiple threads of fork join, and the execution flow of each thread is the same as the second method reduce (identity,accumulator), and the third parameter combiner function is to treat the execution result of each thread as a new stream, and then use the first method reduce (accumulator) process to specify.

/ / after testing, when the number of elements is less than 24:00, the number of parallel threads is equal to the number of elements; when greater than or equal to 24:00, the number of parallel threads is 16List list = Arrays.asList (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24); Integer v = list.stream (). Reduce ((x1, x2)-> x1 + x2). System.out.println (v); / / 300Integer v1 = list.stream (). Reduce (10, (x1, x2)-> x1 + x2); System.out.println (v1); / / 310Integer v2 = list.stream (). Reduce (0, (x1, x2)-> {System.out.println ("stream accumulator: x1:" + x1 + "x2:" + x2); return x1-x2) }, (x1, x2)-> {System.out.println ("stream combiner: x1:" + x1 + "x2:" + x2); return x1 * x2;}); System.out.println (v2); / /-300Integer v3 = list.parallelStream (). Reduce (0, (x1, x2)-> {System.out.println ("parallelStream accumulator: x1:" + x1 + "x2:" return x1-x2) }, (x1, x2)-> {System.out.println ("parallelStream combiner: x1:" + x1 + "x2:" + x2); return x1 * x2;}); System.out.println (v3); / / 197474048

3.3 Collection operation

Collect: receives an Collector instance and collects the elements in the stream into another data structure.

Collector is an interface with the following five abstract methods:

Supplier supplier (): create a result container A

BiConsumer accumulator (): consumer interface, the first parameter is container A, and the second parameter is the element T in the flow.

BinaryOperator combiner (): function interface. The function of this parameter is the same as the combiner parameter in the previous method (reduce). It merges the running results of each child process in the parallel flow (container An after the operation of the accumulator function).

Function finisher (): functional interface. The parameter is Container A, and the return type is R, the final desired result of the collect method.

Set characteristics (): returns an immutable collection of Set to indicate the characteristics of the Collector. There are three characteristics:

CONCURRENT: indicates that this collector supports concurrency. (there are other descriptions in the official document, but I haven't explored it for the time being, so I won't translate too much.)

UNORDERED: indicates that the collection operation does not retain the original order of the elements in the stream.

IDENTITY_FINISH: indicates that the finisher parameter is just an identification and can be ignored.

3.3.1 Collector tool Library: Collectors

Student S1 = new Student ("aa", 10Power1); Student S2 = new Student ("bb", 20Power2); Student S3 = new Student ("cc", 10Power3); List list = Arrays.asList (S1, S2, S3); / / pretending to be listList ageList = list.stream (). Map (Student::getAge) .coach (Collectors.toList ()); / [10,20,10] / / transformed into setSet ageSet = list.stream (). Map (Student::getAge) .conversation (Collectors.toSet ()) / / [20,10] / / converted to map, note: key cannot be the same, otherwise the error Map studentMap = list.stream (). Collect (Collectors.toMap (Student::getName, Student::getAge)); / / {cc=10, bb=20, aa=10} / / string delimiter String joinName = list.stream () .map (Student::getName) .string (Collectors.joining (",", "(", ") / / (aa,bb,cc) / / aggregation operation / / 1. Total number of students Long count = list.stream (). Collect (Collectors.counting ()); / / 3Universe 2. The eldest age (the youngest minBy is the same) Integer maxAge = list.stream (). Map (Student::getAge). Birthday (Collectors.maxBy (Integer::compare)). Get (); / 20. The age of all people is Integer sumAge = list.stream (). Collect (Collectors.summingInt (Student::getAge)); / / 40 Universe 4. Average age Double averageAge = list.stream (). Collect (Collectors.averagingDouble (Student::getAge)); / / 13.33333333333333334 / bring all the above methods DoubleSummaryStatistics statistics = list.stream (). Collect (Collectors.summarizingDouble (Student::getAge)); System.out.println ("count:" + statistics.getCount () + ", max:" + statistics.getMax () + ", sum:" + statistics.getSum () + ", average:" + statistics.getAverage () / / grouping Map ageMap = list.stream () .collect (Collectors.groupingBy (Student::getAge)); / / multiple grouping, first by type and then by age Map typeAgeMap = list.stream () .collect (Collectors.groupingBy (Student::getType, Collectors.groupingBy (Student::getAge) / / Partition / / is divided into two parts, one is older than 10 years old, and the other is less than or equal to 10 years old Map partMap = list.stream (). Collect (v-> v.getAge () > 10); / / Integer allAge = list.stream (). Map (Student::getAge) .partition (Collectors.reducing (Integer::sum)). Get (); / / 40

3.3.2 Collectors.toList () parsing

/ / toList source code public static Collector toList () {return new CollectorImpl ((Supplier) ArrayList::new, List::add, (left, right)-> {left.addAll (right); return left;}, CH_ID);} / / to better understand, let's convert the lambda expression public Collector toList () {Supplier supplier = ()-> new ArrayList (); BiConsumer accumulator = (list, t)-> list.add (t) in the source code BinaryOperator combiner = (list1, list2)-> {list1.addAll (list2); return list1;}; Function finisher = (list)-> list;Set characteristics = Collections.unmodifiableSet (EnumSet.of (Collector.Characteristics.IDENTITY_FINISH)); return new Collector () {@ Overridepublic Supplier supplier () {return supplier;} @ Overridepublic BiConsumer accumulator () {return accumulator;} @ Overridepublic BinaryOperator combiner () {return combiner;} @ Overridepublic Function finisher () {return finisher;} @ Overridepublic Set characteristics () {return characteristics;}} } this is the end of the article on "what are the common methods of Java8 Stream streaming?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "what are the common methods of Java8 Stream streaming". If you want to learn more knowledge, you are welcome to follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report