代码优化小结

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)
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值