4 Core functional interfaces of Java8
1.CONSUMER<T>: Consumer Interface
Demand:
public void happy (double money, consumer<double> Consumer) {
Consumer.accept (Money);
}
@Test
public void Test () {
Happy (E), System.out.println ("Happy consumption" + E + "Yuan");
}
2.supplier<t> Supply-type interface
T get ();
Requirement: Generate a certain number of integers and put them in the collection
Public list<integer> getList (int size, supplier<integer> Supplier) {
list<integer> list = new arraylist<> ();
for (int i = 0; i < size; i++) {
Integer num = Supplier.get ();
List.add (num);
}
return list;
}
@Test
public void Test2 () {
list<integer> list = GetList (ten, ()-(int) (Math.random () *100));
for (Integer Num:
List) {
SYSTEM.OUT.PRINTLN (num);
}
}
3. Function-Type interface
Function<t,r>
R apply<t t>
Requirement: Remove the leading and trailing spaces
public string Strhandler (String str, function<string,string> fun) {
return fun.apply (str);
}
@Test
public void Test3 () {
String Strtrim = Strhandler ("\T\T\TXSJIFCDSNKJFHS", (e)->e.trim ());
System.out.println (Strtrim);
}
4.Predicate Assertion-Type interface
Boolean Test (T-t)
Put a string that satisfies a condition into the collection
Public list<string> getnewlist (list<string> List, predicate<string> Pre) {
list<string> NewList = new arraylist<> ();
for (String str:
List) {
if (Pre.test (str)) {
Newlist.add (str);
}
}
return newlist;
}
@Test
public void Test4 () {
list<string> list = java.util.Arrays.asList ("ADSJ", "Xjsai", "Sdjasio", "ws");
List<string> li = getnewlist (list, (s)->s.length () >3);
for (String str:
Li) {
System.out.println (str);
}
}
4 Core functional interfaces of Java8