流式for循环
private static void test1() {
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
arrayList.add(i + "");
}
arrayList.stream().forEach(e -> System.out.println(Thread.currentThread().getName() + " " + e));
}
并行流式for循环
private static void test2() {
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
arrayList.add(i + "");
}
arrayList.parallelStream().forEach(e -> System.out.println(Thread.currentThread().getName() + " " + e));
}
forkjoin 并行流式for循环
private static final ForkJoinPool pool = new ForkJoinPool(5);
private static void test3() {
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
arrayList.add(i + "");
}
pool.submit(() -> arrayList.parallelStream().forEach(e -> {
System.out.println(Thread.currentThread().getName() + " " + e);
})).join();
}
并行MAP
private static void test4() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1));
List<String> arrayList =new ArrayList<>();
for(int i = 0; i < 100; ++i){
arrayList .add(i + "");
}
Map<String, String> resultMap = arrayList .parallelStream().collect(Collectors.toMap(t -> t, t -> {
try {
threadPoolExecutor.submit(() -> t).get();
} catch (Exception e) {
log.error("异常:{}" + e.getMessage());
}
return "";
}));
}
优化并行MAP
private static void test5() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1));
List<String> arrayList =new ArrayList<>();
for(int i = 0; i < 100; ++i){
arrayList .add(i + "");
}
Map<String, Future<String>> futureMap = arrayList.stream().collect(Collectors.toMap(t -> t, t -> threadPoolExecutor.submit(() -> t),(oldValue, newValue)->newValue));
futureMap.entrySet().stream().collect(Collectors.toMap(e->e.getKey(),e->{
try {
e.getValue().get();
}catch (Exception t) {
log.error("异常:{}" + t.getMessage());
}
return "";
}));
}
执行
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
}
空处理方式
return Optional.ofNullable();
return Lists.newArrayList();
implements DependencyBase, Nullable{}
extends Nullable{}
return Collections.emptyList();
return empty();
return null;
return Optional.empty();
return new NullObject();
return new Object();
return BigDecimal.ZERO;
return Collections.emptyMap();
return Collections.emptySet();