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

How to realize three kinds of functional programming in Java

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

Share

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

This article introduces the relevant knowledge of "how to realize three kinds of functional programming in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

0. Functional programming

Functional programming (Functional Programming) belongs to the language of programming paradigm (Programming Paradigm). In addition, there is imperative programming (Imperative Programing). Interested students can understand it for themselves. Here we roughly explain functional programming. In functional programming, once the input is determined, the output is determined, and the result of the function call only depends on the incoming input variables and internal logic, not on the external. Such a written function has no side effects. For example:

Public class Person {private int a = 1; public int add (int b) {return a + b;} public int pow (int c) {return c * c;} public static void main (String [] args) {Person p = new Person (); p.add (1); p.pow (2);}}

The method add (int b) in the above code does not conform to functional programming. The result of this function call is uncertain, and its result depends not only on b but also on field a. The function pow (int c) is an example of functional programming. As long as it is called, the input value c determines the return value.

In functional programming, a function is also a first-class citizen, can be passed as a parameter, can be assigned, referenced, and can be treated as a data type. You can have a deeper experience if you can use a language such as javascript. If you want to have an in-depth understanding of this programming paradigm, you can search for information on the Internet.

1. Lambda expression

Lambda expression is a new feature in jdk8, which is introduced in functional programming above. Oracle introduced lambda in jdk8, and from then on, functional programming is partially supported in Java.

The syntax structure of the lambda expression in Java: (params)-> expression. It consists of three parts, the first part is the parentheses and the formal parameters inside the parentheses, the second part is the "- >" arrow symbol, and the third part is the expression method body, which can be a code block or an execution expression.

/ / 1. The full form of the lambda expression: input parameters, return values, and code blocks. (int a, int b)-> {int c = a + b; return c;} / / 2. Lambda expressions can also be omitted in some cases / / 2.1.When the contemporary code block does not need to return a value, you can omit the return statement (int a, int b)-> {int c = a + b } / / 2.2 the curly braces / / can be omitted when there is only one sentence in the contemporary code block, and the execution result of this sentence (int a, int b)-> a + b is returned by default in this case. / / the type of parameter with the same function / / 2.3 can be inferred according to the method declaration in the functional interface / / the type of parameter (a, b)-> a + b can be omitted; / / the type of parameter (a, b)-> a + b has the same effect / / 2.4 can be omitted when there is only one parameter, parenthesis a-> a * a

Next, let's show a code that goes from defining an interface to using lambda expressions.

/ * description: * * @ author waxxd * @ version 1.0 * @ date 2019-10-15 * * / public class Test1 {private int a = 1; private int b = 2; / * * this method requires a parameter of type IAdd * @ param add * @ return * * / public int add1 (IAdd add) {return add.add (a);} public static void main (String [] args) {Test1 test1 = new Test1 () / use the lambda expression int c = test1.add1 ((a, b)-> a + b); System.out.println (c); / use the anonymous class int d = test1.add1 (new IAdd () {@ Override public int add (int a, int b) {return a + b;}}); System.out.println (d) }} / * description: * functional interface in which there can be only one * @ author waxxd * @ version 1.0 * @ date 2019-10-15 * * / @ FunctionalInterfacepublic interface IAdd {int add (int a, int b);}

You can see that the way to use lambda expressions is much simpler and more elegant than anonymous class code. Here is a frequently used example of creating threads:

Public class Test () {public static void main (String [] args) {Thread T1 = new Thread (new Runable () {System.out.println ("create threads using anonymous classes"); Thread T2 = new Thread (()-> System.out.println ("create threads using lambda")); t1.start (); t2.start ();}} 2. Double colon:: symbol

This symbol is first seen in C++, in C++ is a similar logo scope parsing symbol or scope symbol, the description may be inaccurate, students interested in C++ can find their own. If you know cantilever, the operation symbol is somewhat similar to the function pointer in C++.:: in Java, it can also be called method reference, and the function mentioned above is also a first-class citizen. Here, it is similar to passing the method as an argument. In the previous example, we use lambda expressions similar to methods that use anonymous classes to implement an interface. However, there is another case where we do not want to implement the interface method ourselves, but just want to pass in a method that has already been implemented, and we can use::, its syntax rules are as follows:

Class name:: static method name or instance of class:: instance method.

List list = new ArrayList;list.forEach (File::getName); / / use a double colon to pass a function in, list.forEach (file-> file.getName ()); / / use the normal lambda expression 3. Optional class

Optional is also a new class in jdk8, which gives us a more elegant way to handle NPE exceptions in the Java language. To some extent, it can replace if judgment and introduce relevant APIs:

Empty creates an empty Optional object

Of and ofNullable

Of creates an Optional object and runs a NPE exception if the passed parameter is empty.

OfNullable is the same as above, but when the incoming parameter is empty, the empty method is called to create an empty Optional object.

Optional of = Optional.of ("waxxd"); / / passing in an empty parameter throws a NullPointerException exception Optional ofNull = Optional.of (null); / / the following two sentences execute Optional ofNullable = Optional.ofNullable ("waxxd") normally; / / call Optional.empty () Optional ofNullableNull = Optional.ofNullable (null) when the parameter is empty

Get/orElse/orElseGet/orElseThrow

/ / get gets the value of the Option package if the value is null, throws a NoSuchElementException exception String aa = Optional.of ("aa") .get (); / / orElse gets the value and returns the default value set by orElse String aa1 = Optional.of ("aa") .orElse ("bb") if the value is empty. / / orElseGet get value if the value is empty, the inner can be an anonymous inner class call that implements the Supplier interface to provide the returned result String aa2 = Optional.of ("aa"). OrElseGet (()-> "aaa" .toUpperCase ()); / / orElseThrow get value if it does not exist, throw the following exception Optional.empty () .orElseThrow (IllegalArgumentException::new) / / practical application, that is, how to optimize if// mentioned above. For example, if you have an API, the user passes the parameter Integer type, and the user can also choose not to pass it. We set the default value for it, 1public void f (Integer type) {if (type = null) {type = 1;} Optional.ofNullable (type) .orElse (1). } "how to implement three kinds of functional programming in Java" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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