Java8函數(shù)式編程之四: 常見的函數(shù)式接口及實(shí)例

上一篇博客中Java8函數(shù)式編程之三:函數(shù)式接口 - 簡(jiǎn)書?留下的問題是關(guān)于Consumer接口的,本篇博客就來介紹一下Java8提供的重要的函數(shù)式接口募判。

1.Consumer接口:

我們首先看一下Consumer接口的Javadoc荡含,比任何資料都正規(guī)的解釋吝羞。

'

/**

* Represents an operation that accepts a single input argument and returns no

* result. Unlike most other functional interfaces, {@codeConsumer} is expected

* to operate via side-effects.

*/

@FunctionalInterface

public interfaceConsumer {

/**

* Performs this operation on the given argument. 通過給定的參數(shù)執(zhí)行操作

*/

voidaccept(Tt);

/**

* Returns a composed {@codeConsumer} that performs, in sequence, this

* operation followed by the {@codeafter} operation. If performing either

* operation throws an exception, it is relayed to the caller of the

* composed operation.? If performing this operation throws an exception,

* the {@codeafter} operation will not be performed.

*/

defaultConsumer andThen(Consumer after) {

Objects.requireNonNull(after);

return(Tt) -> { accept(t);after.accept(t); };

}

}

'

Consumer接口中定義了一個(gè)accept()的抽象方法,它接收泛型T的對(duì)象内颗,沒有返回(void).

一句話解釋就是:接收一個(gè)輸入?yún)?shù),不返回結(jié)果敦腔。

——————————————————————————————————

2.Function接口 :

/**

* Represents a function that accepts one argument and produces a result.

*/

@FunctionalInterface

public interfaceFunction {

/**

* Applies this function to the given argument.

*/

Rapply(Tt);

/**

* Returns a composed function that first applies the {@codebefore}

* function to its input, and then applies this function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default Function compose(Function before) {

Objects.requireNonNull(before);

return(Vv) -> apply(before.apply(v));

}

/**

* Returns a composed function that first applies this function to

* its input, and then applies the {@codeafter} function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default Function andThen(Function after) {

Objects.requireNonNull(after);

return(Tt) ->after.apply(apply(t));

}

/**

* Returns a function that always returns its input argument.

*

*@paramthe type of the input and output objects to the function

*@returna function that always returns its input argument

*/

static Function identity() {

returnt -> t;

}

}

Function接口定義了一個(gè)apply()方法均澳,它接收一個(gè)泛型T的對(duì)象,并返回一個(gè)R對(duì)象符衔。

一句話解釋就是:輸入一個(gè)參數(shù)找前,返回一個(gè)結(jié)果。

——————————————————

Function接口實(shí)例:

public classFunctionTest {

public static voidmain(String[] args) {

FunctionTest test =newFunctionTest();

//現(xiàn)在相當(dāng)于傳遞了一個(gè)行為/動(dòng)作給compute

System.out.print(test.compute(2, value -> {

return2* value;

}));

System.out.print(test.compute(5, value -> {

returnvalue +7;

}));

}

//一個(gè)計(jì)算函數(shù)

public intcompute(inta, Function function) {

returnfunction.apply(a);

}

}

————————————————————————————————————

3.BiFunction函數(shù)式接口:

/**

* Represents a function that accepts two arguments and produces a result.

* This is the two-arity specialization of {@linkFunction}.

*

*

This is afunctional interface

* whose functional method is {@link#apply(Object, Object)}.

*/

@FunctionalInterface

public interfaceBiFunction {

/**

* Applies this function to the given arguments.

*/

Rapply(Tt,Uu);

/**

* Returns a composed function that first applies this function to

* its input, and then applies the {@codeafter} function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default BiFunction andThen(Function after) {

Objects.requireNonNull(after);

return(Tt,Uu) ->after.apply(apply(t, u));

}

}

一句話總結(jié)就是:接收兩個(gè)參數(shù)判族,得到一個(gè)結(jié)果躺盛。

——————

Bifunction實(shí)例:

public classBiFunctionTest {

public static voidmain(String[] atgs) {

BiFunctionTest test =newBiFunctionTest();

System.out.print(test.compute(1,3, (value1, value2) -> value1 + value2));

System.out.print(test.compute(1,3, (value1, value2) -> value1 - value2));

//

System.out.print(test.compute2(3,2, (value1, value2) -> value1 + value2, value -> value - value));

}

public intcompute(inta,intb, BiFunction biFunction) {

returnbiFunction.apply(a, b);

}

//使用andThen

public intcompute2(inta,intb, BiFunction biFunction, Function function) {

returnbiFunction.andThen(function).apply(a, b);

}

}

————————————————————————

4.Predicate函數(shù)式接口:

/**

* Represents a predicate (boolean-valued function) of one argument.

*

*

This is afunctional interface

* whose functional method is {@link#test(Object)}.

*

*@paramthe type of the input to the predicate

*

*@since1.8

*/

@FunctionalInterface

public interfacePredicate {

/**

* Evaluates this predicate on the given argument.

*/

booleantest(Tt);

/**

* Returns a composed predicate that represents a short-circuiting logical

* AND of this predicate and another.? When evaluating the composed

* predicate, if this predicate is {@codefalse}, then the {@codeother}

* predicate is not evaluated.

*/

defaultPredicate and(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) &&other.test(t);

}

/**

* Returns a predicate that represents the logical negation of this

* predicate.

*/

defaultPredicate negate() {

return(t) -> !test(t);

}

/**

* Returns a composed predicate that represents a short-circuiting logical

* OR of this predicate and another.? When evaluating the composed

* predicate, if this predicate is {@codetrue}, then the {@codeother}

* predicate is not evaluated.

*/

defaultPredicate or(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) ||other.test(t);

}

/**

* Returns a predicate that tests if two arguments are equal according

* to {@linkObjects#equals(Object, Object)}.

*/

static Predicate isEqual(Object targetRef) {

return(null== targetRef)

? Objects::isNull

: object ->targetRef.equals(object);

}

}

一句話解釋就是:接收一個(gè)參數(shù),返回一個(gè)布爾值形帮。

Predicate接口里的其他方法:

1.邏輯與

defaultPredicate and(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) &&other.test(t);

}

2.邏輯非 (取反)

defaultPredicate negate() {

return(t) -> !test(t);

}

3.邏輯或

defaultPredicate or(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) ||other.test(t);

}

4.靜態(tài)方法槽惫,相等性/

static Predicate isEqual(Object targetRef) {

return(null== targetRef)

? Objects::isNull

: object ->targetRef.equals(object);

}

——————————

實(shí)例1:

public classPredicateTest {

public static voidmain(String[] args) {

List list = Arrays.asList(1,2,3,4,5,6,7,8,9);

PredicateTest test =newPredicateTest();

//找到集合中所有的奇數(shù)

test.conditionFilter(list, item -> item %2!=0);

//大于5的數(shù)

test.conditionFilter(list, item -> item >5);

//打印所有的元素

test.conditionFilter(list, item ->true);

//測(cè)試與

test.conditionFilter2(list, item -> item >5, item -> item %2==0);

//測(cè)試或

test.conditionFilter3(list, item -> item >5, item -> item %2==0);

//測(cè)試非

test.conditionFilter4(list, item -> item >5, item -> item %2==0);

//相等性判斷

System.out.print(test.isEqual("test").test("test"));

}

//函數(shù)式編程提供了一種更高層次的抽象

public voidconditionFilter(List list, Predicate predicate) {

for(Integer integer : list) {

if(predicate.test(integer)) {

System.out.print(integer +" ");

}

}

}

//與

public voidconditionFilter2(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.and(predicate2).test(integer)) {

System.out.print(integer);

}

}

}

//或

public voidconditionFilter3(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.or(predicate2).test(integer)) {

System.out.print(integer);

}

}

}

//非

public voidconditionFilter4(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.and(predicate2).negate().test(integer)) {

System.out.print(integer);

}

}

}

//想等性判斷

publicPredicate isEqual(Object object) {

returnPredicate.isEqual(object);

}

}

————————————————

5.Supplier函數(shù)式接口:

/**

* Represents a supplier of results.

*

*

There is no requirement that a new or distinct result be returned each

* time the supplier is invoked.

*

*

This is afunctional interface

* whose functional method is {@link#get()}.

*/

@FunctionalInterface

public interfaceSupplier {

/**

* Gets a result.

*/

Tget();

}

一句話解釋就是:不接收任何參數(shù),返回一個(gè)結(jié)果辩撑。

——————————————————————————


public classSupplierTest {

public static voidmain(String[] args){

//不接收參數(shù),返回一個(gè)結(jié)果

Supplier supplier = () ->"hello world";

System.out.print(supplier.get());

}

}

————————————

實(shí)例2:

public classStudent {

privateStringname="zhangsan";

private intage;

publicStudent(){

}

publicStudent(String name,intage){

this.name= name;

this.age= age;

}

publicString getName() {

returnname;

}

public voidsetName(String name) {

this.name= name;

}

public intgetAge() {

returnage;

}

public voidsetAge(intage) {

this.age= age;

}

}

——————————————

public classStudentTest {

public static voidmain(String[] args){

Supplier supplier = () ->newStudent();

System.out.print(supplier.get().getName());

//使用構(gòu)造方法引用

Supplier supplier1 = Student::new;

System.out.print(supplier1.get().getName());

}

}

————————————————

6.BinaryOperator函數(shù)式接口

/**

* Represents an operation upon two operands of the same type, producing a result

* of the same type as the operands.? This is a specialization of

* {@linkBiFunction} for the case where the operands and the result are all of

* the same type.

*

*

This is afunctional interface

* whose functional method is {@link#apply(Object, Object)}.

*/

@FunctionalInterface

public interfaceBinaryOperatorextendsBiFunction {

/**

* Returns a {@linkBinaryOperator} which returns the lesser of two elements

* according to the specified {@codeComparator}.

*/

public static BinaryOperator minBy(Comparator comparator) {

Objects.requireNonNull(comparator);

return(a, b) ->comparator.compare(a, b) <=0? a : b;

}

/**

* Returns a {@linkBinaryOperator} which returns the greater of two elements

* according to the specified {@codeComparator}.

*/

public static BinaryOperator maxBy(Comparator comparator) {

Objects.requireNonNull(comparator);

return(a, b) ->comparator.compare(a, b) >=0? a : b;

}

}

一句話解釋就是:接收兩個(gè)相同類型的參數(shù)界斜,返回一個(gè)結(jié)果。

————————————————

public classBinaryOperatorTest {

public static voidmain(String[] args){

BinaryOperatorTest test =newBinaryOperatorTest();

System.out.print(test.compute(1,2,(a,b) -> a +b));

}

public intcompute(inta,intb, BinaryOperator binaryOperator){

returnbinaryOperator.apply(a,b);

}

publicString getShort(String a, String b, Comparator comparator){

returnBinaryOperator.minBy(comparator).apply(a,b);

}

}

——————————————————————

6.Optinal函數(shù)式接口:

/**

* A container object which may or may not contain a non-null value.

* If a value is present, {@codeisPresent()} will return {@codetrue} and

* {@codeget()} will return the value.

*

*

Additional methods that depend on the presence or absence of a contained

* value are provided, such as {@link#orElse(java.lang.Object) orElse()}

* (return a default value if value not present) and

* {@link#ifPresent(java.util.function.Consumer) ifPresent()} (execute a block

* of code if the value is present).

*/

public final classOptional

一句話解釋就是:為了解決Java中的NPE問題(NullPointerExeception)

(程序員認(rèn)為某個(gè)對(duì)象不會(huì)為空合冀,而去使用這個(gè)對(duì)象調(diào)用某個(gè)方法各薇,導(dǎo)致出現(xiàn)NullPointerExeception)

————————————————

Optinal是一個(gè)容器對(duì)象,里面可以包含或者不包含一個(gè)非空值君躺。如果這個(gè)值存在峭判,isPresent()方法會(huì)返回true,get()方法會(huì)返回這個(gè)值棕叫。

——————

幾個(gè)工廠方法構(gòu)造對(duì)象

1.構(gòu)造一個(gè)值為null的對(duì)象

public static Optional empty() {

@SuppressWarnings("unchecked")

Optional t = (Optional)EMPTY;

returnt;

}

2.構(gòu)造一個(gè)不為null的對(duì)象

public static Optional of(Tvalue) {

return newOptional<>(value);

}

3.構(gòu)造出可能為null林螃,也可能不為null的對(duì)象

public static Optional ofNullable(Tvalue) {

returnvalue ==null?empty() :of(value);

}

————————————————————

4.取值get();

publicTget() {

if(value==null) {

throw newNoSuchElementException("No value present");

}

returnvalue;

}

5.判斷對(duì)象是否存在 isPresent()

public booleanisPresent() {

returnvalue!=null;

}

——————————————

public classOptionalTest {

public static voidmain(String[] args){

//不能new,需要用工廠方法創(chuàng)建

Optional optional = Optional.of("hello");

optional.ifPresent(item -> System.out.print(item));

//如果里面沒有值俺泣,就打出word

System.out.print(optional.orElse("world"));

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末治宣,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子砌滞,更是在濱河造成了極大的恐慌侮邀,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,248評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贝润,死亡現(xiàn)場(chǎng)離奇詭異绊茧,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)打掘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門华畏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鹏秋,“玉大人,你說我怎么就攤上這事亡笑÷乱模” “怎么了?”我有些...
    開封第一講書人閱讀 153,443評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵仑乌,是天一觀的道長(zhǎng)百拓。 經(jīng)常有香客問我,道長(zhǎng)晰甚,這世上最難降的妖魔是什么衙传? 我笑而不...
    開封第一講書人閱讀 55,475評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮厕九,結(jié)果婚禮上蓖捶,老公的妹妹穿的比我還像新娘。我一直安慰自己扁远,他們只是感情好俊鱼,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評(píng)論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著畅买,像睡著了一般亭引。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上皮获,一...
    開封第一講書人閱讀 49,185評(píng)論 1 284
  • 那天焙蚓,我揣著相機(jī)與錄音,去河邊找鬼洒宝。 笑死购公,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的雁歌。 我是一名探鬼主播宏浩,決...
    沈念sama閱讀 38,451評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼靠瞎!你這毒婦竟也來了比庄?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,112評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤乏盐,失蹤者是張志新(化名)和其女友劉穎佳窑,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體父能,經(jīng)...
    沈念sama閱讀 43,609評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡神凑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片溉委。...
    茶點(diǎn)故事閱讀 38,163評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鹃唯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瓣喊,到底是詐尸還是另有隱情坡慌,我是刑警寧澤,帶...
    沈念sama閱讀 33,803評(píng)論 4 323
  • 正文 年R本政府宣布藻三,位于F島的核電站洪橘,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏趴酣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評(píng)論 3 307
  • 文/蒙蒙 一坑夯、第九天 我趴在偏房一處隱蔽的房頂上張望岖寞。 院中可真熱鬧,春花似錦柜蜈、人聲如沸仗谆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)隶垮。三九已至,卻和暖如春秘噪,著一層夾襖步出監(jiān)牢的瞬間狸吞,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評(píng)論 1 261
  • 我被黑心中介騙來泰國(guó)打工指煎, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蹋偏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,636評(píng)論 2 355
  • 正文 我出身青樓至壤,卻偏偏與公主長(zhǎng)得像威始,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子像街,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容

  • “您好镰绎,我們新店開業(yè)脓斩,只需耽誤您幾分鐘,請(qǐng)您進(jìn)店看看畴栖,我們有小禮品相送俭厚。”小F低頭看看手表驶臊,離朋友約定的時(shí)間還有一...
    妞妞飛閱讀 348評(píng)論 0 1
  • 沒錯(cuò),這是一篇蹭熱的文章…… 人之初扛门,性本善鸠信。也正因如此,人們的評(píng)判總是站在道德的至高點(diǎn)论寨,比如說到出軌星立,比如談到婚...
    雨歇夢(mèng)微涼閱讀 144評(píng)論 0 0
  • 今天是正月十二,第四天葬凳。 可樂出國(guó)的第四天绰垂。在所有人都還在回味越來越?jīng)]有年味的新年時(shí),她一個(gè)人火焰,拖著行李劲装,去了馬來...
    蠟筆并不新閱讀 265評(píng)論 0 0
  • 最近正在給果果讀繪本故事,雖然他現(xiàn)在還聽不懂昌简,但是已經(jīng)從一開始的不在意占业,到現(xiàn)在,自己能夠拿著讀過的繪本書翻來翻去纯赎,...
    盡力了嗎閱讀 505評(píng)論 0 0
  • 和游總聊天谦疾,不是一家人不進(jìn)一家門啊。很多思想竟然會(huì)碰撞到一起犬金。平時(shí)不溝通竟然也可以想到一起去念恍。。晚顷。這就是能量場(chǎng)效應(yīng)...
    Yao_3019閱讀 165評(píng)論 0 0