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

相关推荐
凤凰院凶涛QAQ8 小时前
《Java版数据结构 & 集合类剖析》Map & Set & 反射:“从哈希碰撞到红黑树转换,反射帮你扒开 HashMap 的桶数组看个究竟”
java·数据结构·算法
H.莓飛8 小时前
【数据结构】排序_OJ题(一):计数、桶与排序后的处理
java·开发语言·数据结构
w_zero_one10 小时前
算法--模拟
java·数据结构·算法
fish_zzzz15 小时前
笔记-论数据结构1
数据结构
青春不朽51216 小时前
Python 的 list append 为什么是均摊 O(1)?拆开过度分配那张表,看容量翻倍背后的暗账
java·python·list
傅科摆 _ py17 小时前
链表力扣复习
数据结构·leetcode·链表
inrichtt19 小时前
第十一课时:串口中断接收与回调函数实战解析
c语言·数据结构·stm32·单片机·嵌入式硬件
信奥卷王19 小时前
[GESP202406 六级] 二叉树(含视频)
数据结构·算法
starzy199021 小时前
KafkaProducer 源码深度剖析:支撑高吞吐的数据结构设计
大数据·数据结构·kafka
罗湖老棍子1 天前
【例 1】Sightseeing Trip(信息学奥赛一本通- P1494)(洛谷-P10927)
数据结构·算法·图论·最短路·floyd·最小环