這篇文章主要講解了如何分類(lèi)和使用java中functional interface,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

創(chuàng)新互聯(lián)建站是一家專(zhuān)注于網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站與策劃設(shè)計(jì),龍?zhí)毒W(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:龍?zhí)兜鹊貐^(qū)。龍?zhí)蹲鼍W(wǎng)站價(jià)格咨詢(xún):13518219792
java 8引入了lambda表達(dá)式,lambda表達(dá)式實(shí)際上表示的就是一個(gè)匿名的function。
在java 8之前,如果需要使用到匿名function需要new一個(gè)類(lèi)的實(shí)現(xiàn),但是有了lambda表達(dá)式之后,一切都變的非常簡(jiǎn)介。
我們看一個(gè)之前講線程池的時(shí)候的一個(gè)例子:
//ExecutorService using class
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Runnable() {
@Override
public void run() {
log.info("new runnable");
}
});executorService.submit需要接收一個(gè)Runnable類(lèi),上面的例子中我們new了一個(gè)Runnable類(lèi),并實(shí)現(xiàn)了它的run()方法。
上面的例子如果用lambda表達(dá)式來(lái)重寫(xiě),則如下所示:
//ExecutorService using lambda
executorService.submit(()->log.info("new runnable"));看起是不是很簡(jiǎn)單,使用lambda表達(dá)式就可以省略匿名類(lèi)的構(gòu)造,并且可讀性更強(qiáng)。
那么是不是所有的匿名類(lèi)都可以用lambda表達(dá)式來(lái)重構(gòu)呢?也不是。
我們看下Runnable類(lèi)有什么特點(diǎn):
@FunctionalInterface public interface Runnable
Runnable類(lèi)上面有一個(gè)@FunctionalInterface注解。這個(gè)注解就是我們今天要講到的Functional Interface。
Functional Interface
Functional Interface是指帶有 @FunctionalInterface 注解的interface。它的特點(diǎn)是其中只有一個(gè)子類(lèi)必須要實(shí)現(xiàn)的abstract方法。如果abstract方法前面帶有default關(guān)鍵字,則不做計(jì)算。
其實(shí)這個(gè)也很好理解,因?yàn)镕unctional Interface改寫(xiě)成為lambda表達(dá)式之后,并沒(méi)有指定實(shí)現(xiàn)的哪個(gè)方法,如果有多個(gè)方法需要實(shí)現(xiàn)的話(huà),就會(huì)有問(wèn)題。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}Functional Interface一般都在java.util.function包中。
根據(jù)要實(shí)現(xiàn)的方法參數(shù)和返回值的不同,Functional Interface可以分為很多種,下面我們分別來(lái)介紹。
Function:一個(gè)參數(shù)一個(gè)返回值
Function接口定義了一個(gè)方法,接收一個(gè)參數(shù),返回一個(gè)參數(shù)。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);一般我們?cè)趯?duì)集合類(lèi)進(jìn)行處理的時(shí)候,會(huì)用到Function。
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("name", s -> s.length());上面的例子中我們調(diào)用了map的computeIfAbsent方法,傳入一個(gè)Function。
上面的例子還可以改寫(xiě)成更短的:
Integer value1 = nameMap.computeIfAbsent("name", String::length);Function沒(méi)有指明參數(shù)和返回值的類(lèi)型,如果需要傳入特定的參數(shù),則可以使用IntFunction, LongFunction, DoubleFunction:
@FunctionalInterface
public interface IntFunction<R> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
R apply(int value);
}如果需要返回特定的參數(shù),則可以使用ToIntFunction, ToLongFunction, ToDoubleFunction:
@FunctionalInterface
public interface ToDoubleFunction<T> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
double applyAsDouble(T value);
}如果要同時(shí)指定參數(shù)和返回值,則可以使用DoubleToIntFunction, DoubleToLongFunction, IntToDoubleFunction, IntToLongFunction, LongToIntFunction, LongToDoubleFunction:
@FunctionalInterface
public interface LongToIntFunction {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
int applyAsInt(long value);
}BiFunction:接收兩個(gè)參數(shù),一個(gè)返回值
如果需要接受兩個(gè)參數(shù),一個(gè)返回值的話(huà),可以使用BiFunction:BiFunction, ToDoubleBiFunction, ToIntBiFunction, ToLongBiFunction等。
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);我們看一個(gè)BiFunction的例子:
//BiFunction
Map<String, Integer> salaries = new HashMap<>();
salaries.put("alice", 100);
salaries.put("jack", 200);
salaries.put("mark", 300);
salaries.replaceAll((name, oldValue) ->
name.equals("alice") ? oldValue : oldValue + 200);Supplier:無(wú)參的Function
如果什么參數(shù)都不需要,則可以使用Supplier:
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}Consumer:接收一個(gè)參數(shù),不返回值
Consumer接收一個(gè)參數(shù),但是不返回任何值,我們看下Consumer的定義:
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);看一個(gè)Consumer的具體應(yīng)用:
//Consumer nameMap.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
Predicate:接收一個(gè)參數(shù),返回boolean
Predicate接收一個(gè)參數(shù),返回boolean值:
@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);如果用在集合類(lèi)的過(guò)濾上面那是極好的:
//Predicate
List<String> names = Arrays.asList("A", "B", "C", "D", "E");
List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());Operator:接收和返回同樣的類(lèi)型
Operator接收和返回同樣的類(lèi)型,有很多種Operator:UnaryOperator BinaryOperator ,DoubleUnaryOperator, IntUnaryOperator, LongUnaryOperator, DoubleBinaryOperator, IntBinaryOperator, LongBinaryOperator等。
@FunctionalInterface
public interface IntUnaryOperator {
/**
* Applies this operator to the given operand.
*
* @param operand the operand
* @return the operator result
*/
int applyAsInt(int operand);我們看一個(gè)BinaryOperator的例子:
//Operator List<Integer> values = Arrays.asList(1, 2, 3, 4, 5); int sum = values.stream() .reduce(0, (i1, i2) -> i1 + i2);
Functional Interface是一個(gè)非常有用的新特性,希望大家能夠掌握。
看完上述內(nèi)容,是不是對(duì)如何分類(lèi)和使用java中functional interface有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當(dāng)前文章:如何分類(lèi)和使用java中functionalinterface
轉(zhuǎn)載來(lái)于:http://chinadenli.net/article32/gsjgsc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、網(wǎng)站營(yíng)銷(xiāo)、網(wǎng)站內(nèi)鏈、網(wǎng)站設(shè)計(jì)、App設(shè)計(jì)、服務(wù)器托管
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)