Overview of three function interfaces
The JDK pre-defines a number of function interfaces to avoid repeated user definitions. The most typical is Function:
@FunctionalInterface Public Interface Function<t, r> { R apply (T t);}
This interface represents a function that takes a parameter of type T and returns a return value of type R.
Another predefined function interface is called Consumer, and the only difference with function is that it has no return value.
@FunctionalInterface Public Interface Consumer<t> { void accept (T-T);}
There is also a predicate, used to determine whether a condition is satisfied. It is often used for sieve filtering operations:
@FunctionalInterface Public Interface Predicate<t> { boolean Test (T-t);}
In summary, a lambda expression is actually defined as an anonymous method, except that this method must conform to at least one function interface.
Basic Application Pojo
Public class Emp { privateint empno; Private String ename; // getter|setter|tostring slightly Public Static void printemp (emp emp) { System.out.println ("empno:" +emp.getempno () + "\nename:" +emp.getename ());} }
Static list
Static list<emp> emps = arrays.aslist ( new emp (1, "yw"), new emp (2, "YT") ), new emp (3, "YP"), new emp (4, "YC"));
predicate applications
@Test Public void testpredicate () { predicate<Emp> predicate = Emp-Emp.getempno () >1; for (Emp e:emps) { if(Predicate.test (e)) { emp.printemp (e); }}}
Run
function application
@Test Public void testfunction () { // extract name of employee function<emp,string> Function = Emp Emp.getename (); for (Emp emp:emps) { = function.apply (EMP); System.out.println (ename); }}
Run
Consumer applications
@Test Public void Testconsumer () { Consumer<Emp> Consumer = Emp::p rintemp; for (Emp e:emps) { consumer.accept (e); }}
Run
Comprehensive application of preprocessing functions
Private void printEmpNameWhenEmpNoLg1 (iterable<t> source,predicate<t> predicate,function<t,r> function, Consumer<R> Consumer) { for(T t:source) { if( Predicate.test (t)) { = function.apply (t); Consumer.accept (R);}} }
This function contains four parameters, respectively, for the list (in this case, Emps) and three predefined function interfaces that implement the Iterable interface. The application is as follows:
@Test Public void Testfunctioninterface () { predicate<Emp> predicate = Emp-Emp.getempno () >1; function<Emp,String> function = Emp -emp.getename (); Consumer<String> Consumer = system.out::p rintln; PRINTEMPNAMEWHENEMPNOLG1 (Emps,predicate,function,consumer);}
Run
JAVA8 Learning Notes (ii)----three predefined interfaces