全程无废话,上代码,记录方便自己查阅。
package com.hsj;import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Test;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;/*** @author hsj* @description:CompletableFuture stream 处理demo* @date 2023-8-31 14:53*/
public class StreamTest {@Testpublic void test(){ArrayList<String> list = Lists.newArrayList("H", "S", "J");//返回值list.stream().map((str) -> CompletableFuture.supplyAsync(() -> String.format("%s-return-value",str))).collect(Collectors.toList()).stream()//等待每一个CompletableFuture线程完成.map(CompletableFuture::join).collect(Collectors.toList()).forEach(System.out::println);//没有返回值ArrayList<STestBean> list002 = Lists.newArrayList(STestBean.builder().build(),STestBean.builder().build(),STestBean.builder().build());list002.stream().map((sTestBean) -> CompletableFuture.runAsync(() -> {sTestBean.setAge(18);sTestBean.setName("HSJ");})).collect(Collectors.toList()).stream().map(CompletableFuture::join);list002.stream().forEach((sTestBean) -> System.out.println(sTestBean));}
}@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
class STestBean{private int age;private String name;
}