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 Java function programming

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you the example analysis of Java function programming. I hope you will get something after reading this article. Let's discuss it together.

1. Functional programming Lambda

We can think of the lambda expression as an anonymous function, which can be assigned to a variable and passed to a method that accepts a function interface as a parameter. The Lambda expression does not have a name, but it has a parameter list, a body, and a return type.

(parameters)-> expression

Lambda expressions can be used in the context of a function interface.

1. Interface

A function interface is an interface that specifies only one abstract method.

Public interface Comparator {int compare (T1, T2);} public interface Runnable {void run ();}

Lambda expressions allow us to directly inline the implementation of abstract methods that provide function interfaces and treat the entire expression as an instance of a function interface.

Function descriptor:

We call the signature of an abstract method of a function interface a function descriptor. The function descriptor describes the signature of the lambda expression. For example, we can think of Runnable's function descriptor as ()-> void because it has an abstract method that accepts nothing and returns nothing (void).

2. Java function interface 1, Predicate

The Predicate interface defines an abstract method called test, which accepts an object of generic type T and returns a Boolean value. This interface can be used to represent Boolean expressions that use T-type objects.

Function descriptor: t-> boolean

@ FunctionalInterfacepublic interface Predicate {boolean test (T t);} 2, Consumer

The java.util.function.Consumer interface defines an abstract method called accept that accepts an object of generic type T and does not return any void. We can use this interface when we need to access T-type objects and perform some operations on them.

Function descriptor: t-> void

3 、 Function

The java.util.function.function interface defines an abstract method called apply that takes an object of generic type T as input and returns an object of generic type R. This interface can be used when we need to define a lambda to map information from the input object to the output.

Function descriptor: t-> R

4 、 Supplier

The interface java.util.function.Supplier defines an abstract method called get that accepts nothing and returns an object of type T.

Function descriptor: ()-> R

Primitive Specializations

The primitive interface is a dedicated interface to avoid automatic boxing when the input or output is a primitive.

Public interface IntPredicate {boolean test (int t);} III. Type checking

The type of lambda is derived from the context of using lambda. The type required by a lambda expression in context (for example, a method parameter passed to it or a local variable assigned to it) is called the target type. Lambda expressions can get their target types from the assignment context, the method call context (parameters and returns), and the cast context.

Object o = (Runnable) ()-> System.out.println ("Hello"); 1. Capturing Lambda

Lambda can capture (reference in its body) instance and static variables without restrictions. But when local variables are captured, they must be explicitly declared as final or actually final.

Why do we have this restriction?

Instance variables are stored on the heap, while local variables are on the stack. If lambda has direct access to local variables and lambda is used in threads, threads using lambda can attempt to access the variable after the thread that assigned the variable has unassigned it. Therefore, Java implements access to free local variables as access to its copy rather than to the original variable. If a local variable is assigned only once, it makes no difference, so there is a limitation.

4. Method reference

There are three main methods for reference:

Method references to static methods. For example,-Integer::parseInt

A method reference to any type of instance method. Example-String::length

Method reference to an instance method of an existing object or expression. Example-student::getRank, where student is a local variable of type student with method getRank

List list = Arrays.asList ("a", "b", "A", "B"); list.sort ((S1, S2)-> s1.compareToIgnoreCase (S2))

It can be written as

List list = Arrays.asList ("a", "b", "A", "B"); list.sort (String::compareToIgnoreCase); 1. Constructor reference

You can use ClassName::new to reference an existing constructor

Supplier supplier = ArrayList::new; is the same as Supplier supplier = ()-> new ArrayList ()

2. Combined Lambda

Many function interfaces contain default methods that can be used to combine lambda expressions. Example of combination-

Combine two predicates into a larger predicate to perform an or operation between the two predicates

Reverse or chain comparator

3 、 Comparators

Arrange the students in reverse order

Comparator c = Comparator.comparing (Student::getRank); students.sort (comparing (Student::getRank). Reversed ())

Sort the students by name (reverse), and then sort them in reverse order

Students.sort (comparing (Student::getName). Reversed () .thencomparing (Student::getRank)); Predicates

The Predicates interface includes three methods: negate, and, and or, which can be used to create more complex predicates.

Predicate naturalNumber = I-> I > 0; Predicate naturalNumberLessThanHundred = naturalNumber.and (I-> I)

< 100);4、Functions 函数接口带有两个默认方法,andThen和compose。 Consider f(x) = x2 and g(x) = x3 + 1 then g(f(x)) ->

Function square = n-> n*n*n+1; Function squareAndCube = square.andThen (n-> n*n*n+1); System.out.println (squareAndCube.apply (2)); 65

F (g (x))->

Function square = n-> n*n*n; Function squareAndCube = square.compose (n-> n*n*n + 1); System.out.println (squareAndCube.apply (2))

Apply Lambda

Let's look at how to write a general method to filter a set of books based on the veratain attribute (think of it as the where clause of sql).

Public static List filter (Predicate where) {List books = Catalogue.books (); return books.stream () .filter (where) .requests (Collectors.toList ());}

Lambda expressions filter different books through different filters

List javaBook = filter (book-> book.getCategory (). Equals (JAVA)); List joshuaBlochBook = filter (book-> book.getAuthor (). Equals ("Joshua Bloch")); after reading this article, I believe you have some understanding of "sample Analysis of Java function programming". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

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