CompletableFuture用于异步处理
1、异步执行,不支持返回值
CompletableFuture.runAsync(()->{
});
2、支持返回值
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(()->{
return 1L;
});
3、异步执行后处理其他工作
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
return 1;
}).handle(new BiFunction<Integer, Throwable, Integer>() {
@Override
public Integer apply(Integer param, Throwable throwable) {
int result = -1;
if(throwable==null){
result = param * 2;
}else{
System.out.println(throwable.getMessage());
}
return result;
}
});
https://www.jianshu.com/p/6bac52527ca4
Optional.ofNullable用于防止造成空指针
public static <T> List<T> of(List<T> source) {
return Optional.ofNullable(source).orElse(Lists.newArrayListWithCapacity(0));
}
1、isPresent()方法用于判断是否有值
2、map() 如果有值,则对其执行调用映射函数得到返回值。如果返回值不为 null,则创建包含映射返回值的Optional作为map方法返回值,否则返回空Optiona
String str = "1";
Optional<String> optional = Optional.ofNullable(str).map(MyOptional::getBeanName);
public static String getBeanName(String value){
return StringUtils.isNotEmpty(value)?"beanName"+value:"beanName";
}
3、filter用于过滤符合条件的内容
String str = "a1";
Optional<String> optional = Optional.ofNullable(str).filter(s->s.startsWith("a"));
stream方法用于声明方式处理数据
http://www.runoob.com/java/java8-streams.html
class MyBean{
private int id;
private String value;
MyBean(int id,String value){
this.id = id;
this.value = value;
}
public int getId(){
return id;
}
public String getValue(){
return value;
}
}
List<MyBean> list = Arrays.asList(new MyBean(1,"name1"),new MyBean(2,"name2"),new MyBean(2,"name12"),new MyBean(3,"value3"));
1、map 方法用于映射每个元素到对应的结果
List<Integer> ids = list.stream().map(MyBean::getId).collect(Collectors.toList());
2、filter 方法用于通过设置的条件过滤出元素
List<MyBean> myBeans = list.stream().filter(item->item.value.startsWith("name")).collect(Collectors.toList());
3、sorted 方法用于对流进行排序
myBeans = list.stream().sorted((i,j)->j.id - i.id).collect(Collectors.toList());
4、过滤重复值
ids = list.stream().map(item->item.getId()*2).distinct().collect(Collectors.toList());
5、判断满足某个条件
boolean anyMatch = list.stream().anyMatch(item->item.getValue().startsWith("name"));
6、判断是否满足所有条件
boolean allMatch = list.stream().allMatch(item->item.getValue().startsWith("name"));
7、获取对象中任何一个项
MyBean myBean = list.stream().findAny().orElse(null);
8、获取第一个满足的项
myBean = list.stream().findFirst().orElse(null);
9、截取获取前面多少项
myBeans = list.stream().limit(2).collect(Collectors.toList());
10、截取获取从多少项开始的后面项
myBeans = list.stream().skip(1).collect(Collectors.toList());
11、summaryStatistics用于统计,获取最大值、平均数等
LongSummaryStatistics longSummaryStatistics = map.values().stream().mapToLong(entify->entify.getId()).summaryStatistics();
List<Long> longList = Arrays.asList(1L,2L,5L,6L);
longSummaryStatistics = longList.stream().mapToLong(item->item).summaryStatistics();
System.out.println(longSummaryStatistics);
12、用于将list项的对象中按照某个列转换成map,进行分组
Map<Integer,List<MyBean>> maps = list.stream().collect(Collectors.groupingBy(MyBean::getId));
13、用于将list转成map,不能有重复的key
list = Arrays.asList(new MyBean(1, "name1"), new MyBean(2, "name12"), new MyBean(3, "value3"));
Map<Integer,MyBean> map = list.stream().collect(Collectors.toMap(MyBean::getId, Function.identity()));
使用coundown加快查询速度
private static ThreadPoolExecutor createExecutorService(int corePoolSize, int maximumPoolSize, long keepAliveTime, int blockingQueueSize, String businessName) {
return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(blockingQueueSize),
(r, e) -> log.error(businessName + " Executor reject task info={}", e)
);
}
private ThreadPoolExecutor poolExecutor = createExecutorService(20, 40, 5, 1000, "UserQuery");
List<Runnable> runnables = Lists.newArrayList();
runnables.add(() -> {
});
CountDownLatch countDownLatch = new CountDownLatch(runnables.size());
runnables.forEach(r -> poolExecutor.submit(() -> {
try {
r.run();
} catch (Exception e) {
log.error("query order other error", e);
} finally {
countDownLatch.countDown();
}
}));
try {
countDownLatch.await(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.error("query order await error", e);
}
使用Pair返回两个参数,优化代码返回
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
import org.apache.commons.lang3.tuple.Pair;
public Pair<Boolean,Long> getValue(){
return Pair.of(true,1L)
}