4 Core functional interfaces of Java8

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.