Java8 中的常用函式式介面

2021-09-11 05:08:07 字數 3098 閱讀 5062

函式式介面: predicate < t >

函式描述符: t ==> boolean

原始型別特化:intpredicate, longpredicate, doublepredicate

// 判斷是否是正數

intpredicate predicate = i -

>

(i >0)

;// true

predicate.

test(5

);

函式式介面: consumer < t >

函式描述符: t ==> void

原始型別特化:intconsumer,longconsumer, doubleconsumer

// 輸出數字到控制台

intconsumer consumer = i -

> system.out.

println

(i);

//intconsumer consumer = system.out::println;

// 5

consumer.

accept(5

);

函式式介面: function

函式描述符: t ==> r

原始型別特化:

intfunction < r >, inttodoublefunction, inttolongfunction,

longfunction < r >, longtodoublefunction, longtointfunction,

doublefunction < r >,

tointfunction < t >, todoublefunction < t >, tolongfunction < t >

// 整型轉字串

intfunction

int2stringfunc = i -

>

(i +"")

;//"10"

int2stringfunc.(10

);// 字串轉整型

tointfunction

string2intfunc = s -

> integer.

parseint

(s);

//tointfunctionstring2intfunc = integer::parseint;

// 22

string2intfunc.

("22"

);

函式式介面: supplier < t >

函式描述符: () ==> t

原始型別特化:booleansupplier,intsupplier, longsupplier, doublesupplier

// 無中生有

supplier

supplier =()

->

"welcome to my blog"

;// "welcome to my blog"

supplier.

get(

);

函式式介面: unaryoperator < t >

函式描述符: t ==> t

原始型別特化:intunaryoperator, longunaryoperator, doubleunaryoperator

// 平方

intunaryoperator operator = i -

> i * i;

// 25

operator.(5

);

函式式介面: binaryoperator< t >

函式描述符: (t, t) ==> t

原始型別特化:intbinaryoperator, longbinaryoperator, doublebinaryoperator

// 兩數之和

intbinaryoperator sum =

(i, j)

-> i + j;

// 11

sum.(5

,6);

函式式介面: bipredicate < l, r >

函式描述符: (l, r) ==> boolean

原始型別特化:無

// 判斷數值是否相等

bipredicate

bipredicate =

(i, s)

-> i == integer.

parseint

(s);

// true

bipredicate.

test(5

,"5");

// false

bipredicate.

test(5

,"4"

);

函式式介面: biconsumer < t, u >

函式描述符: (t, u) ==> void

原始型別特化:objintconsumer < t >, objlongconsumer < t >, objdoubleconsumer < t >

string format =

"%s is %d years old"

; biconsumer

biconsumer =

(s, i)

->

;// tom is 15 years old

biconsumer.

accept

("tom",15

);

函式式介面: bifunction < t, u, r >

函式描述符: (t, u) ==> r

原始型別特化:tointbifunction < t, u >, todoublebifunction < t, u >, tolongbifunction < t, u >

// 加入hashmap中

bifunction

bifunction =

(s, i)

->

;//

bifunction.

("key"

,100

);

Java8 常用函式式介面

本文主要參考 在此感謝 接收乙個引數t,沒有返回值 原始碼 functionalinte ce public inte ce consumer 示例 講述乙個學生在學習過程中,需要買學習用品。買什麼東西是具體的實現,我們在呼叫study 方法的時候再指定。test public void testc...

Java8常用的函式式介面

1 predicate 斷言型介面 傳入的字串是否以 sql 結尾 predicateisendwithsql s s.endswith sql 傳入的字串非 sql 結尾 predicatenotendwithsql isendwithsql.negate boolean test isendwi...

java 8 函式式介面

functionalinte ce public inte ce personsearch functionalinte ce public inte ce personsearch1 functionalinte ce public inte ce personsearch2 方法的預設實現 介面...