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

Example Analysis of flow processing in java8

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "sample analysis of stream processing in java8", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of stream processing in java8".

I'll just give you an example of how elegant Stream is.

/ / A pair of apples Map appleCount = apples.stream () .apples by color (groupingBy (Apple::getColor, counting (); / / filter out the black apples and summarize the total amount of apples Double sum = apples.stream () .filter (I-> "black" .equals (i.getColor () .apples (toList)

1. Lambda expression

Although this article focuses on stream, you need to pass lambda expressions in stream, so let's briefly introduce lambda expressions. Lambda expressions are actually anonymous functions (anonymous function), which are functions or subroutines that do not need to define identifiers.

The representation of anonymous functions in java, leaving only the contents of the input parameters and method body

/ / ordinary function public void run (String s) {System.out.print (s + "");} / / I don't want a name! (s)-> System.out.print (s + "")

Well, we used to use object adjustment methods in the past. When do you use this nameless thing?

In java, we use this anonymous function through a functional interface.

Functional interface

The 1.java contains only an interface for an unimplemented method. There can be methods with the same name as in Object and default methods (interface methods in java8 can have default implementations).

The functional interface in 2.java is annotated with @ FunctionalInterface. Runnable and Comparator are all functional interfaces.

3.java.util.function package provides us with many commonly used functional interfaces, such as Function and so on.

Examples of usage:

/ / implement the run method in Runnable to replace the anonymous inner class. Runnable r = ()-> System.out.print (""); / / passed as a parameter. New Thread (()-> System.out.println ("")). Start (); ArrayList list = new ArrayList (); list.forEach (I-> System.out.println (i.getWeight (); / / simplified policy mode public static List filterApples (List inventory,ApplePredicate p) {List apples = new ArrayList (); for (Apple apple: inventory) {if (p.test (apple)) {apples.add (apple);}} return apples } public class BigApple implement ApplePredicate {@ Override public boolean test (Apple a) {if (a.getWeight > 10) {return a}} / / this is a simple policy mode. Different interface ApplePredicate implementation classes are created according to the needs of users, and different implementation classes are passed in when calling. But the problem is that if there are too many requirements, many implementation classes will be created, which is too bloated and not easy to manage. Xx.filterApple (inventory,new BigApple); / / use lambda expressions and no longer need to create the BigApple class xx.filterApple (inventory,i- > (i.getWeight > 10))

Using lambda expressions can simplify a lot of template code and pass code directly to methods.

Anyway,

The method input and output parameters come from the functional interface

/ / enter parameter s, return void (s)-> System.out.println (s); / / enter empty parameter, return void ()-> System.out.print (""); / / enter parameter I, return iparameter 1i-> iparameter 1max / write code block apple- > {if (apple.getWeiht > 5) return "BIG"; else return "small";}

All right, don't talk too much, if you are interested, recommend the following article or the first three chapters of "Java8 practice".

What is the use of 1.Lambda expressions? How to use it?

2.java8 actual combat

II. Stream

What is stream?

A new member of Java API, which allows you to work with data collections declaratively (similar to sql, expressed by query statements rather than temporarily writing an implementation).

If someone says that lambda expressions are not easy to understand, that's barely acceptable (too complex lambda is missing and not easy to read, but usually lambda doesn't do too complex implementations), but streams are really easy to understand and use. This grammatical sugar is really sweet.

Note:

1. The stream can only be used once, and the end of traversal means that the stream is consumed.

two。 The operation of the flow to the collection belongs to the internal iteration, and it is the flow that helps us to operate, not the external iteration.

3. The stream operation includes three parts: the data source, the intermediate operation chain and the terminal operation.

Basic flow operation

List collect = list.stream () / filter out black apples. Filter (I-> "black" .equals (i.getColor () / / Let Apple sort by weight by price. Sorted (Comparator.comparing (Apple::getWeight) .thencomparing (I-> i.getPrice ()) / / filter out duplicate data. Distinc t () / / only Apple's price .map (Apple::getPrice) / / only the first two pieces of data are left. Limit (2) / / returns .limit (toList ()) in the form of a collection. / / the element list.forEach (I-> System.out.print (I)) in the circular print list

Apple::getPrincei-> i.getPrince () can be thought of as a syntax candy that only involves a single method, and the effect is the same as the lambda expression, but it is more readable.

The same principle

The following is a list of common actions

Middle

Operation type action function description function filter Intermediate filter T-> booleanPredicatesorted Intermediate sort (TMagazine T)-> intComparatormap Intermediate Mapping T-> RFunctionlimit Intermediate truncation

Remove the weight in the middle of distinct, according to the equals method

Skip the first n elements in the middle of skip

Terminal

The operation type functions each element in the consumption flow of the forEach terminal. It uses lambda to operate the number of elements returned by the count terminal, and the longcollect terminal reduces the stream to a set, such as List,Map or even Integer.

Screening and slicing

List strings = Arrays.asList ("Hello", "World"); List collect1 = strings.stream () / String maps to String [] .map (I-> i.split (")) / / Arrays::Stream data array and returns a stream String []-> Stream / / flatMap each array is not mapped to a stream, but the content mapped into a stream Stream- > Stream .flatMap (Arrays::stream) .map (toList ()); System.out.println (collect) -> output [H, e, l, l, o, W, o, r, l, d]

Reduction operation reduce

List integers = Arrays.asList (12,3,45,3,2); / / superposition operation Integer reduce = integers.stream (). Reduce (3, (I, j)-> I + j); Integer reduce2 = integers.stream (). Reduce (5, (x, y)-> x

< y ? x : y);// 无初始值的叠加操作Optional reduce1 = integers.stream().reduce((i, j) ->

I + j); / / maximum without initial value Optional reduce4 = integers.stream () .reduce (Integer::min); / / maximum without initial value Optional reduce5 = integers.stream () .reduce (Integer::max); / / summation Optional reduce6 = integers.stream () .reduce (Integer::sum)

What reduce does is take two numbers, and the result returns the next number, and so on.

Optional is a new class introduced by java8 to avoid null pointer exceptions. When the collection is empty, the result will be wrapped in Optional. You can use the isPresent () method to determine whether it is null or not.

May be empty without an initial value, so Optional is returned

Middle

The operation type action function describes the function flatmap so that the passed stream returns the content T-> booleanPredicate.

Terminal

The operation type acts on the anyMatch terminal to return boolean, to determine whether there is a qualified content noneMatch terminal to return boolean, to determine whether there is no qualified content allMatch terminal to return boolean, to judge that it is all qualified content findAny terminal Optional, to randomly find an element to return findFirst terminal Optional, to return the first element reduce terminal Optional (T)-> T reduction operation

Numerical flow

Various operations of packaging types will have unpacking operation and packing operation, which seriously affect the performance. So Java8 provides us with the raw stream of values.

/ / OptionalDouble average = apples.stream () .mapToDouble (Apple::getPrice) .average (); / / Numeric flow summation OptionalDouble average = apples.stream () .mapToDouble (Apple::getPrice) .sum (); / / numeric flow to find the maximum, if not returned 2double v = apples.stream () .mapToDouble (Apple::getPrice) .max () .orElse (2); / generate random number IntStream s = IntStream.rangeClosed (1100)

The following is a list of common numeric flow operations

Middle

Operation types function rangeClosed (1100) intermediate generate random number (1100] range (1100) intermediate generate random number (1100) boxed () wrapped into general stream mapToObj intermediate returned as object stream mapToInt intermediate mapped to numerical stream

Terminal, terminal operation is similar to List general stream

Build flow

Value creation

Stream s = Stream.of ("java", "python")

Array creation

Int [] I = {2pm 3pm 4J 5}; Stream = Arrays.stream (I)

Generated by files, NIO API has been updated to take advantage of Stream API

Stream s = Files.lines (Paths.get ("data.txt"), Charset.defaultCharset ())

Flow created by function: infinite flow

/ iterative Stream.iterate (0penn-> nail2) .limit (10) .forEach (System.out::println); / / generate, need to pass the new value Stream.generate (Math.random) .limit (5) .forEach (System.out::println) provided by Lambda of type Supplier. This is all the content of the article "sample Analysis of flow processing in java8". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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: 202

*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