成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Function 與 CompletableFuture 的組合使用指南

開發 前端
在Java編程領域,函數式接口和異步編程是提升代碼靈活性和性能的重要手段。Function作為函數式接口的代表,提供了簡潔的函數式編程風格;CompletableFuture則為異步任務處理帶來了極大的便利。

前言

Java編程領域,函數式接口和異步編程是提升代碼靈活性和性能的重要手段。Function作為函數式接口的代表,提供了簡潔的函數式編程風格;CompletableFuture則為異步任務處理帶來了極大的便利。將FunctionCompletableFuture結合使用,能夠在異步操作中實現強大的數據轉換和流程控制。

Function 接口詳解

Function接口是Java 8引入的函數式接口,位于java.util.function包中。它代表了一個接受一個參數并返回一個結果的函數,其定義如下:

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

其中,T是輸入參數的類型,R是返回結果的類型。apply方法是該接口的抽象方法,用于執行具體的函數邏輯。

基本使用

通過實現apply方法,可以定義具體的函數操作。例如,將一個字符串轉換為大寫形式:

public class FunctionExample {
    public static void main(String[] args) {
        Function<String, String> toUpperCaseFunction = String::toUpperCase;
        String result = toUpperCaseFunction.apply("hello");
        System.out.println(result); // 輸出: HELLO
    }
}

接口的組合

andThen方法:先執行當前函數,再將結果作為參數傳遞給另一個函數:

Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> composedFunction = square.andThen(addOne);
int result = composedFunction.apply(2);
System.out.println(result); // 輸出: 5(先平方得4,再加1)

compose方法:先執行傳入的函數,再將結果作為參數傳遞給當前函數:

Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> composedFunction = square.compose(addOne);
int result = composedFunction.apply(2);
System.out.println(result); // 輸出: 9(先加1得3,再平方)

CompletableFuture 詳解

CompletableFutureJava 8引入的用于異步編程的類,它實現了Future接口和CompletionStage接口,提供了豐富的方法來處理異步任務的創建、組合和結果獲取。

基本使用

使用supplyAsync方法創建有返回值的異步任務:

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000); // 模擬耗時操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, CompletableFuture!";
        });
        // 異步獲取結果
        future.thenAccept(System.out::println);
    }
}

使用runAsync方法創建無返回值的異步任務:

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Task completed without return value");
});

結果處理與組合

thenApply方法:在異步任務完成后,對結果進行轉換:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5)
       .thenApply(x -> x * 2);
future.thenAccept(System.out::println); // 輸出: 10

thenCompose方法:用于組合兩個CompletableFuture,將前一個任務的結果作為后一個任務的輸入:

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<Integer> future2 = future1.thenCompose(x -> CompletableFuture.supplyAsync(() -> x * 2));
future2.thenAccept(System.out::println); // 輸出: 10

thenCombine方法:將兩個CompletableFuture的結果進行合并處理:

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (x, y) -> x + y);
combinedFuture.thenAccept(System.out::println); // 輸出: 8

Function 與 CompletableFuture 的結合應用

在 thenApply 中使用 Function

thenApply方法接受一個Function作為參數,在異步任務完成后對結果進行轉換。例如,從數據庫異步獲取用戶ID,然后根據ID查詢用戶信息:

class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class CombinedExample {
    public static CompletableFuture<Integer> getUserIdAsync() {
        return CompletableFuture.supplyAsync(() -> 1);
    }

    public static User getUserById(int id) {
        return new User(id, "John Doe");
    }

    public static void main(String[] args) {
        Function<Integer, User> idToUserFunction = CombinedExample::getUserById;
        CompletableFuture<User> userFuture = getUserIdAsync()
               .thenApply(idToUserFunction);
        userFuture.thenAccept(user -> System.out.println("User: " + user.getName()));
    }
}

組合使用

在更復雜的場景中,可能需要組合多個CompletableFutureFunction。例如,先異步獲取訂單ID,再根據訂單ID獲取訂單詳情,最后對訂單詳情進行處理:

class Order {
    private int id;
    private String details;

    public Order(int id, String details) {
        this.id = id;
        this.details = details;
    }
}

class OrderService {
    public static CompletableFuture<Integer> getOrderIdAsync() {
        return CompletableFuture.supplyAsync(() -> 1);
    }

    public static Order getOrderById(int id) {
        return new Order(id, "Order details for " + id);
    }

    public static String processOrder(Order order) {
        return"Processed: " + order.getDetails();
    }
}

public class ComplexCombinedExample {
    public static void main(String[] args) {
        Function<Integer, Order> idToOrderFunction = OrderService::getOrderById;
        Function<Order, String> orderToProcessedFunction = OrderService::processOrder;

        CompletableFuture<String> processedOrderFuture = OrderService.getOrderIdAsync()
               .thenApply(idToOrderFunction)
               .thenApply(orderToProcessedFunction);

        processedOrderFuture.thenAccept(System.out::println);
    }
}

批量使用

class UserService {
    public static CompletableFuture<UserDetail> getUserDetailAsync(int userId) {
        return CompletableFuture.supplyAsync(() -> {
            // 模擬耗時操作,如數據庫查詢
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 假設根據userId生成用戶詳情
            return new UserDetail(userId, "user" + userId, "user" + userId + "@example.com");
        });
    }
}

public class Main {
    public static void main(String[] args) {
        List<Integer> userIds = new ArrayList<>();
        userIds.add(1);
        userIds.add(2);
        userIds.add(3);

        // 定義一個Function,將用戶ID轉換為獲取用戶詳情的CompletableFuture
        Function<Integer, CompletableFuture<UserDetail>> pipeline = UserService::getUserDetailAsync;

        List<CompletableFuture<UserDetail>> tasks = userIds.stream()
               .map(pipeline)
               .collect(Collectors.toList());

        CompletableFuture<List<UserDetail>> resultFuture =
                CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0]))
                       .thenApply(v -> tasks.stream().map(CompletableFuture::join).toList());

        // 等待所有任務完成并獲取結果
        resultFuture.join().forEach(System.out::println);
    }
}

注意事項

異常處理:在CompletableFuture的異步操作中,需要注意異常處理。可以使用exceptionally方法來處理異步任務中的異常:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Something went wrong");
}).exceptionally(ex -> {
    if (ex instanceof TimeoutException) return "TIMEOUT";
    if (ex instanceof BusinessException) return "BUSINESS_FAIL";
    return "UNKNOWN";
});
future.thenAccept(System.out::println);

線程池管理:在使用supplyAsyncrunAsync方法時,可以指定自定義的線程池,以更好地管理異步任務的執行:

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            // 異步任務邏輯
        }, executorService);
        // 關閉線程池
        executorService.shutdown();
    }
}

避免過度嵌套:在組合多個CompletableFuture時,要避免過度嵌套,以免代碼變得難以閱讀和維護。可以使用thenCompose等方法進行扁平化處理。

責任編輯:武曉燕 來源: 一安未來
相關推薦

2022-09-29 09:07:08

DataGrip數據倉庫數據庫

2012-12-26 12:41:14

Android開發WebView

2011-07-21 14:57:34

jQuery Mobi

2009-12-28 17:40:10

WPF TextBox

2021-07-27 10:09:27

鴻蒙HarmonyOS應用

2010-09-06 14:24:28

ppp authent

2021-01-12 15:19:23

Kubernetes

2009-12-31 17:17:45

Silverlight

2025-07-02 09:00:24

ES運維JSON

2010-08-05 15:40:21

FlexBuilder

2017-01-04 15:22:57

TrimPath模板引擎

2010-08-04 15:37:31

Flex圖表

2010-06-03 17:27:36

Hadoop命令

2025-06-10 08:20:00

IDEA編碼開發

2023-10-25 14:51:38

MySQL數據庫JSON

2009-11-30 13:15:27

PHP模板Smarty

2010-12-12 11:27:00

PGP使用指南

2010-08-04 14:28:01

Flex組件

2024-02-04 00:00:00

Loki性能查詢

2022-06-23 08:01:36

FlaskSocketIOSwift
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美一区二区三区在线观看视频 | 国产日韩一区二区三区 | 亚洲一区二区三区免费在线观看 | www.xxxx欧美| 国产美女在线观看 | 91久久国产综合久久 | 久久精品亚洲精品 | 日韩中文字幕免费在线 | 免费精品久久久久久中文字幕 | 天天影视亚洲综合网 | 欧美精品在线一区 | 夜夜摸天天操 | 国产精品久久久久久av公交车 | 国产精品夜间视频香蕉 | 欧美日韩久久久 | 国产精品三级久久久久久电影 | 男人天堂久久 | 日韩欧美在 | 99爱在线| 日韩欧美一区二区三区免费看 | 久久国产区 | 亚洲国产aⅴ成人精品无吗 欧美激情欧美激情在线五月 | 羞羞的视频在线观看 | 亚洲国产福利视频 | 国产福利在线小视频 | 亚洲午夜精品一区二区三区他趣 | www.av7788.com | 国产精品一区二区免费看 | 久草视频在线播放 | 国产视频黄色 | 国产一区二区日韩 | www.日本精品 | 亚洲欧美视频一区 | 久久久久久久久淑女av国产精品 | 亚洲电影一区二区三区 | 色综合一区二区 | 亚洲高清在线 | 婷婷毛片| 欧美精品久久久久 | 91高清视频 | 在线成人www免费观看视频 |