小編這次要給大家分享的是Java中如何實(shí)現(xiàn)Predicate及Consumer接口函數(shù),文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
公司主營(yíng)業(yè)務(wù):成都做網(wǎng)站、成都網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開(kāi)發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開(kāi)放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。成都創(chuàng)新互聯(lián)公司推出嘉禾免費(fèi)做網(wǎng)站回饋大家。
Predicate函數(shù)編程
Predicate功能判斷輸入的對(duì)象是否符合某個(gè)條件。官方文檔解釋到:Determines if the input object matches some criteria.
了解Predicate接口作用后,在學(xué)習(xí)Predicate函數(shù)編程前,先看一下Java 8關(guān)于Predicate的源碼:
@FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t); default Predicate<T> and(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) && other.test(t); } default Predicate<T> negate() { return (t) -> !test(t); } default Predicate<T> or(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) || other.test(t); } static <T> Predicate<T> isEqual(Object targetRef) { return (null == targetRef) ? Objects::isNull : object -> targetRef.equals(object); } }
從上面代碼可以發(fā)現(xiàn),Java 8新增了接口的默認(rèn)(default)方法和(static)靜態(tài)方法。在Java 8以前,接口里的方法要求全部是抽象方法。但是靜態(tài)(static)方法只能通過(guò)接口名調(diào)用,不可以通過(guò)實(shí)現(xiàn)類的類名或者實(shí)現(xiàn)類的對(duì)象調(diào)用;默認(rèn)(default)方法只能通過(guò)接口實(shí)現(xiàn)類的對(duì)象來(lái)調(diào)用。
接下來(lái)主要來(lái)使用接口方法test,可以使用匿名內(nèi)部類提供test()方法的實(shí)現(xiàn),也可以使用lambda表達(dá)式實(shí)現(xiàn)test()。
體驗(yàn)一下Predicate的函數(shù)式編程,使用lambda實(shí)現(xiàn)。其測(cè)試代碼如下:
@Test public void testPredicate(){ java.util.function.Predicate<Integer> boolValue = x -> x > 5; System.out.println(boolValue.test(1));//false System.out.println(boolValue.test(6));//true }
第1行代碼:定義一個(gè)Predicate實(shí)現(xiàn),入?yún)镮nteger,返回傳入?yún)?shù)與5做比較。
第2,3行代碼調(diào)用第一行,傳入相關(guān)參數(shù)。
Consumer函數(shù)編程
Consumer接口的文檔聲明如下:
An operation which accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.
即接口表示一個(gè)接受單個(gè)輸入?yún)?shù)并且沒(méi)有返回值的操作。不像其它函數(shù)式接口,Consumer接口期望執(zhí)行帶有副作用的操作(Consumer的操作可能會(huì)更改輸入?yún)?shù)的內(nèi)部狀態(tài))。
同樣,在了解Consumer函數(shù)編程前,看一下Consumer源代碼,其源代碼如下:
@FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); /** * Returns a composed {@code Consumer} that performs, in sequence, this * operation followed by the {@code after} 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 {@code after} operation will not be performed. * * @param after the operation to perform after this operation * @return a composed {@code Consumer} that performs in sequence this * operation followed by the {@code after} operation * @throws NullPointerException if {@code after} is null */ default Consumer<T> andThen(Consumer<? super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } }
從上面代碼可以看出,Consumer使用了Java 8接口新特性——接口默認(rèn)(default)方法。接下來(lái)使用接口方法accept,體驗(yàn)一下Consumer函數(shù)編程。其測(cè)試代碼如下:
@Test public void testConsumer(){ User user = new User("zm"); //接受一個(gè)參數(shù) Consumer<User> userConsumer = User1 -> User1.setName("zmChange"); userConsumer.accept(user); System.out.println(user.getName());//zmChange }
在Java 8之前的實(shí)現(xiàn)如下:
@Test public void test(){ User user = new User("zm"); this.change(user); System.out.println(user.getName());//輸出zmChange } private void change(User user){ user.setName("zmChange"); }
Predicate和Consumer綜合應(yīng)用
為了詳細(xì)說(shuō)明Predicate和Consumer接口,通過(guò)一個(gè)學(xué)生例子:Student類包含姓名、分?jǐn)?shù)以及待付費(fèi)用,每個(gè)學(xué)生可根據(jù)分?jǐn)?shù)獲得不同程度的費(fèi)用折扣。
Student類源代碼:
public class Student { String firstName; String lastName; Double grade; Double feeDiscount = 0.0; Double baseFee = 2000.0; public Student(String firstName, String lastName, Double grade) { this.firstName = firstName; this.lastName = lastName; this.grade = grade; } public void printFee(){ Double newFee = baseFee - ((baseFee * feeDiscount)/100); System.out.println("The fee after discount: " + newFee); } }
然后分別聲明一個(gè)接受Student對(duì)象的Predicate接口以及Consumer接口的實(shí)現(xiàn)類。本例子使用Predicate接口實(shí)現(xiàn)類的test()方法判斷輸入的Student對(duì)象是否擁有費(fèi)用打折的資格,然后使用Consumer接口的實(shí)現(xiàn)類更新輸入的Student對(duì)象的折扣。
public class PredicateConsumerDemo { public static Student updateStudentFee(Student student, Predicate<Student> predicate, Consumer<Student> consumer){ if (predicate.test(student)){ consumer.accept(student); } return student; } }
Predicate和Consumer接口的test()和accept()方法都接受一個(gè)泛型參數(shù)。不同的是test()方法進(jìn)行某些邏輯判斷并返回一個(gè)boolean值,而accept()接受并改變某個(gè)對(duì)象的內(nèi)部值。updateStudentFee方法的調(diào)用如下所示:
public class Test { public static void main(String[] args) { Student student1 = new Student("Ashok","Kumar", 9.5); student1 = updateStudentFee(student1, //Lambda expression for Predicate interface student -> student.grade > 8.5, //Lambda expression for Consumer inerface student -> student.feeDiscount = 30.0); student1.printFee(); //The fee after discount: 1400.0 Student student2 = new Student("Rajat","Verma", 8.0); student2 = updateStudentFee(student2, //Lambda expression for Predicate interface student -> student.grade >= 8, //Lambda expression for Consumer inerface student -> student.feeDiscount = 20.0); student2.printFee();//The fee after discount: 1600.0 } }
看完這篇關(guān)于Java中如何實(shí)現(xiàn)Predicate及Consumer接口函數(shù)的文章,如果覺(jué)得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。
新聞名稱:Java中如何實(shí)現(xiàn)Predicate及Consumer接口函數(shù)
網(wǎng)頁(yè)地址:http://chinadenli.net/article30/jggppo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營(yíng)銷型網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、定制網(wǎng)站、App設(shè)計(jì)、ChatGPT、定制開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)