20230904工作心得:集合应该如何优雅判空?

1 集合判空

复制代码
        List<String> newlist = null;
        //空指针
        if( !newlist.isEmpty()){
           newlist.forEach(System.out::println);
        }
        //空指针
        if(newlist.size()>0 && newlist!=null){
            newlist.forEach(System.out::println);
        }
        //可行
        if(newlist!=null && newlist.size()>0){
           newlist.forEach(System.out::println);
        }
        //可行 
        if(CollectionUtils.isEmpty(newlist)){
            System.out.println("newlist为空");
        }

其中CollectionUtils是springframework里的方法.

2 Hibernate findAllByXX ?

3 list 转 map 出错。

复制代码
        //出错。brandList有值,但是无法传递给groupMap 
        Map<String, String> groupMap = new HashMap<>();
        if(!brandList.isEmpty()){
            groupMap = brandList.stream().collect(Collectors.toMap(Brand::getBrand,Brand::getCastBrand));
        }

        //最后用了这个方法
        Map<String, String> groupMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(groupMap)){
            groupMap.putAll(brandList.stream().collect(Collectors.toMap(Brand::getBrand,Brand::getCastBrand)));
        }

4 list的lambda操作

1对多映射:根据手机号分组,拿手机号对应的一批数据

复制代码
Map<String, List<String>> groupMap = brandList
.stream()
.collect(Collectors.groupingBy(Brand::getBrand,Collectors.mapping(Brand::getCastBrand,Collectors.toList())));

1对1映射:相当于把一个集合数据,从中抽离出两列key-value

复制代码
 Map<String, String> groupMap = brandList.stream()
.collect(Collectors.toMap(Brand::getBrand,Brand::getCastBrand),(k1,k2)->k1));

这里有个潜在的问题,如果产生了重复的key,会报错。所以需要加后面的(k1,k2)->k1),这个表示如果有冲突,用旧的值。

优雅:

对集合过滤之后,然后针对里面每个元素操作,如果每个元素里有个string,你还可以切割,然后往map里存。

5 map里getOrDefault(key,default).有效防止空指针

6 string 切完之后 是数组。然后再 arrays.aslist 变成 list

7 巧用redis 做次数限制。

这个还挺实用的,比如对解密次数的限制,对个数的限制等等。

8 数据库里别用limit作为字段名,limit是关键字啊哥哥。

相关推荐
程序员莫小特3 小时前
老题新解|大整数加法
数据结构·c++·算法
小刘max4 小时前
深入理解队列(Queue):从原理到实践的完整指南
数据结构
蒙奇D索大4 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
洲覆4 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
MoRanzhi12034 小时前
15. Pandas 综合实战案例(零售数据分析)
数据结构·python·数据挖掘·数据分析·pandas·matplotlib·零售
WIN赢6 小时前
【二叉树的递归算法与层序遍历算法】
数据结构
Zzzzmo_7 小时前
【Java】杨辉三角、洗牌算法
java·数据结构·算法
岑梓铭8 小时前
《考研408数据结构》第四章(串和串的算法)复习笔记
数据结构·笔记·考研·算法
胖咕噜的稞达鸭9 小时前
缝合怪deque如何综合list和vector实现及仿函数模板如何优化priority_queue实现
数据结构·c++·算法·链表·list
暴力求解10 小时前
数据结构---栈和队列详解(下)
数据结构