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是关键字啊哥哥。

相关推荐
BizzZ_2 小时前
算法(1)——双指针
数据结构
Doubbbbbbble云2 小时前
内存碎片化对数据结构操作性能的影响研究4
数据结构
xiangyun614 小时前
【408数据结构 03】线性表与顺序表:C++手写SeqList
开发语言·数据结构·c++
爱吃苹果的日记本5 小时前
数据结构第三课补充(空间复杂度)
数据结构·学习
多弗朗皮卡丘5 小时前
数据结构6:队列
c语言·数据结构
xxxiugou1235 小时前
双指针解题秘籍:从入门到精通
c语言·数据结构·c++·算法
Logic1016 小时前
C语言/数据结构位运算题解:异或XOR找出地铁规划中的“独特坐标“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
沉淀的.晴天6 小时前
FreeRTOS信号量
数据结构·算法
青山木6 小时前
Hot 100 --- 打家劫舍
java·数据结构·算法·leetcode·动态规划
YSL0701247 小时前
线性表和顺序表
数据结构