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 use Java functional interface

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

Share

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

This article mainly introduces "how to use Java functional interface". In daily operation, I believe many people have doubts about how to use Java functional interface. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Java functional interface". Next, please follow the editor to study!

1.1 Overview of functional interfaces

Functional interface: an interface with one and only one abstract method

Functional programming in Java embodies Lambda expressions, so functional interfaces can be used with Lambda.

Only by ensuring that the interface can have only one and only one abstract method can Lambda derive smoothly.

Check whether the interface is a functional interface:

@ FunctionalInterface

Put it above the interface definition: if the interface is a functional interface, the compilation passes, otherwise it fails.

Note:

When we define the functional interface ourselves, @ FunctionalInterface is optional, even if we don't write it, as long as we explode the requirements of the functional interface definition. But it is recommended to add notes.

1.2 functional interface as a parameter of the method

If the parameter of the method is a functional interface, we can pass it as a parameter using the Lambda expression

Define a class (RunnableDemo). Provide two methods in the class

One method is the startThread (Runnable r) method parameter Runnable is a functional interface

One method is the main method. Using the startThread method in the main method

Public class RunnableDemo {public static void main (String [] args) {/ / use the startThread method / / anonymous inner class startThread (new Runnable () {@ Override public void run) in the main method. ) {System.out.println (Thread.currentThread () .getName () + "thread startup") }}); / / Lambda startThread (()-> System.out.println (Thread.currentThread () .getName () + "thread startup")) } private static void startThread (Runnable r) {/ / method parameter Runnable is a numeric interface / / Thread t = new Thread (r); / / t.start (); new Thread (r). Start ();}}

Results:

Thread-0 thread startup

Thread-1 thread startup

1.3 functional interface as the return value of the method

If the return value of the method is a functional interface, we can use the Lambda expression to return as a result

Exercise:

Define a class (ComparatorDemo). Provide two methods in the class

One method is that the Comparotorestring getComparator () method returns "Comparator is a" numeric interface.

One method is the main method. Call the getComparator method in the main method

Public class ComparatorDemo {public static void main (String [] args) {/ / Construction uses scenarios to define collections based on string length / /, storing string elements ArrayList array = new ArrayList (); array.add ("Collin"); array.add ("Leon") Array.add ("Pi"); array.add ("123"); array.add (" 878 "); System.out.println (" before sorting: "+ array); Collections.sort (array); System.out.println (" after sorting: "+ array) Collections.sort (array, getComparator ()); System.out.println ("after sorting:" + array) } private static Comparator getComparator () {/ / anonymous inner class implementation / / sort by length / / Comparator comp = new Comparator () {/ @ Override// public int compare (String o1) String O2) {/ / return o1.length ()-o2.length () / /} / /} / / return comp / / improve / / return new Comparator () {/ @ Override// public int compare (String o1, String O2) {/ / return o1.length ()-o2.length (); / /} / /} / / improved to Lambda expression / / return ((String S1, String S2)-> {/ / return s1.length ()-s2.length (); / / optimized return (S1, S2)-> s1.length ()-s2.length ();}}

Results:

Before sorting: [Collin, Leon, Pi, 123,878]

After sorting: [123,878, Collin, Leon, Pi]

After sorting: [Pi, 123,878, Leon, Collin]

1.4 Common functional interfaces

Java8 predefines a large number of functional interfaces under the java.util.function package.

Functional interface java.Util.Function {public R apply (T t);}: interface has a parameter and returns a parameter

Consumer interface Consumer {public void accept (T t);}: no need to return

Provisioning interface Supplier {public T get ();}

Assertive interface Predicate {public boolean test (T t);}: judge the use of

1.5 Supplier interface

Mainly used to produce data

Supplier

< T >

Contains a method with no parameters

T get (): get the result

This method takes no parameters and returns a data according to some implementation logic (implemented by Lambda expressions)

Supplier

< T >

An interface is also called a production interface. If we determine what type of interface's generics are, then the get method in the interface will produce what type of data for us to use.

Public class SupplierDemo {public static void main (String [] args) {/ / String s = getstring (()-> {/ / return "Hello Java"; / /}); / / optimize String s = getstring (()-> "slightly"); System.out.println (s) Integer I = getInteger (()-> 9920); System.out.println (I);} / / define a method that returns an int data private static Integer getInteger (Supplier sup) {return sup.get () } / / define a method that returns an String data private static String getstring (Supplier sup) {return sup.get ();}}

Results:

Slightly

9920

1.6 Customer interface

Consumer

< T >

Contains two methods

Void accept (T t): performs this operation on the specified parameter

Default Consumer

< T >

And Then (Consumer after): returns a combined Consumer, performs the operation in turn, and then performs the after operation

This interface is also known as a consumer interface, and the type of data it consumes is specified by generics.

Public static void main (String [] args) {operatorString ("Leo1", (String s)-> {System.out.println (s);}); / / optimize operatorString ("Leo2", s-> System.out.println (s)) / / method references operatorString ("Leo3", System.out::println); operatorString ("Leo4", s-> System.out.println (new StringBuilder (s). Reverse ()); System.out.println ("-") OperatorString ("Leon5", s-> System.out.println (s), s-> System.out.println (new StringBuilder (s). Reverse () } / / set a method to consume the same string data twice in different ways: private static void operatorString (String name, Consumer con1,Consumer con2) {/ / con1.accept (name); / / con2.accept (name); con1.andThen (con2) .accept (name) / / consume name first, then con2} / / set a method to consume a string data private static void operatorString (String name, Consumer con) {con.accept (name);}}

Results:

Leo1

Leo2

Leo3

4oeL

-

Leon5

5noeL

Practice

String [] strArray= {"Lin Qingxia 30", "Maggie Cheung, 35", "Wang Zuxian, 33")

There are multiple pieces of information in the string array. Please print out the information in the format "name: XX age: XX".

Request:

Use the act of printing a name as an L ambda instance of the first Consumer interface

Take the action of printing age as the second ambda instance of Consumer connecting [].

Combine two Consumer interfaces in order to use them

Public class ConsumerTest {public static void main (String [] args) {String [] strArray= {"Lin Qingxia, 30", "Maggie Cheung, 35", "Wang Zuxian, 33"}; printInfo (strArray, (String str)-> {String name = str.split (",") [0] System.out.print ("Name:" + name);}, (String str)-> {int age = Integer.parseInt (str.split (",") [1]); System.out.println (", Age:" + age);}) System.out.println ("-") / / improve printInfo (strArray, str-> System.out.print ("Name:" + str.split (",") [0]), str-> System.out.println (", Age:" + Integer.parseInt (str.split (") ") [1]) } private static void printInfo (String [] strArray, Consumer con1, Consumer con2) {for (String str: strArray) {con1.andThen (con2) .accept (str);}

Results:

Name: Lin Qingxia, Age: 30

Name: Maggie Cheung, Age: 35

Name: Wang Zuxian, Age: 33

-

Name: Lin Qingxia, Age: 30

Name: Maggie Cheung, Age: 35

Name: Wang Zuxian, Age: 33

1.7Predicate interface

Predicate

< T >

Four commonly used methods

Boolean test (T t): determines a given parameter (the judgment logic is implemented by a Lambda expression) and returns a Boolean value

Default Predicate negate (): returns a logical negation that corresponds to a logical non

Default Predicate and (Predicate other): returns a combination judgment that corresponds to a short circuit and

Default Predicate or (Predicate other): returns a combination judgment that corresponds to a short circuit or

Predicate

< T >

Interface is usually used to determine whether a parameter meets the specified condition

Practice

String [] strArray= {"Lin Qingxia, 30", "Liu Yan, 34", "Maggie Cheung, 35", "Diao Chan, 31", "Wang Zuxian, 33"}

There are multiple pieces of information in the string array. Please filter the strings that meet the requirements into the set ArrayList through the assembly of the Predicate interface, and then traverse the ArrayList collection.

At the same time, the following requirements are met:

The name length is greater than 2.

Over 33 years old

Analysis.

There are two conditions for judging, so you need to use two Predicate [] to judge the conditions.

Two conditions must be met at the same time, so you can use the and method to connect two judgment conditions.

Public class PredicateTest {public static void main (String [] args) {String [] strArray= {"Lin Qingxia, 30", "Liu Yan, 34", "Maggie Cheung, 35", "Diao Chan, 31", "Wang Zuxian, 33"} ArrayList array = myFilter (strArray, s-> s.split (",") [0] .length () > 2, s-> Integer.parseInt (s.split (",") [1]) > 33) For (String str: array) {System.out.println (str) }} / / filter the strings that meet the requirements into the collection ArrayList through the assembly of the Predicate interface private static ArrayList myFilter (String [] strArray, Predicate pre1, Predicate pre2) {/ / define a collection ArrayList array = new ArrayList () / / traversal array for (String str: strArray) {if (pre1.and (pre2) .test (str)) {array.add (str);}} return array;}}

Results:

Maggie Cheung, 35

1.8 Function interface

Function: several commonly used methods

R apply (T t): applies this function to a given parameter

Default

< V >

Function andThen (Function after): returns a combined function, first applying the function to the input, and then applying the after function to the results

The Function interface is typically used to process parameters, convert (the processing logic is implemented by Lambda expressions), and then return a new arguments

Practice

String s = "Lin Qingxia 30"

Please follow the requirements I specified:

1: intercept the string to get the number age part

2: convert the age string from the previous step to data of type int

3: add the int data in the previous step to 70 to get an int result, which is output in the console

Please use Function interface to realize function stitching.

Public class FunctionTest {public static void main (String [] args) {String s = "Lin Qingxia, 30"; convert (s, ss-> s.split (",") [1], ss-> Integer.parseInt (ss), I-> I + 70) } private static void convert (String s, Function fun1, Function fun2, Function fun3) {int I = fun1.andThen (fun2) .andThen (fun3) .apply (s); System.out.println (I);}}

Results:

one hundred

At this point, the study on "how to use the Java functional interface" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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