ComplateFeature基本使用

  • combine 合并feature
import cn.hutool.http.HttpUtil;
import entity.EssBptPrice;
import entity.Student;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AppTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Student student = new Student();
        student.setName("jzhangsan");
        EssBptPrice essBptPrice = new EssBptPrice();
        essBptPrice.setCreatedBy("wangwu");

        CompletableFuture<List<Student>> studentFeature = CompletableFuture.supplyAsync(() -> {
            List<Student> list = new ArrayList<>();
            list.add(student);
            return list;
        });

        CompletableFuture<List<EssBptPrice>> essFeature = CompletableFuture.supplyAsync(() -> {
            List<EssBptPrice> essBptPrices = new ArrayList<>();
            essBptPrices.add(essBptPrice);
            return essBptPrices;
        });
        //合并两个feature
        CompletableFuture<List<String>> commonfeature = studentFeature.thenCombine(essFeature, (s, e) -> merge(s, e));
        for (String s : commonfeature.get()) {
            System.out.println("合并后输出:" + s);
        }
    }

    public static List<String> merge(List<Student> student, List<EssBptPrice> listCompletableFuture) {
        List<String> list = new ArrayList<>();
        student.forEach(x -> list.add(x.getName()));
        listCompletableFuture.forEach(y -> list.add(y.getCreatedBy()));
        return list;
    }
}
  • thenApply
/**
     * feature 之后进行相关操作
     * @param studentFeature
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void thenApply(CompletableFuture<List<Student>> studentFeature) throws ExecutionException, InterruptedException {
        List<Student> students = studentFeature.thenApply(x -> {
            x.forEach(y -> y.setName(y.getName() + "999"));
            return x;
        }).get();
        students.forEach(x-> System.out.println(x.getName()));
    }
  • compose
 /**
     * 生成新的feature
     * @param studentFeature
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void thenCompose(CompletableFuture<List<Student>> studentFeature) throws ExecutionException, InterruptedException {
        List<Student> students = studentFeature.thenCompose(x -> CompletableFuture.supplyAsync(() -> {
            x.forEach(y -> y.setName(y.getName() + "8888"));
            return x;
        })).get();
        students.forEach(x-> System.out.println(x.getName()));
    }

 

posted @ 2024-03-27 11:56  洞玄巅峰  阅读(21)  评论(0编辑  收藏  举报