Java8集合filter过滤Integer数值为空问题解决方案
来源:互联网 发布:大内义兴数据 编辑:程序博客网 时间:2024/06/14 09:56
问题描述
项目使用mysql,主键使用int自增,实体映射为Integer,而自增主键势必会大于127,那么问题来了 ,使用java8循环做parentId(类似菜单,多层级)判断时候怎么办呢?
示例
//id 是传递的父id 用来过滤用 ,可以为空 List<Channel> channels = allchannel.stream() .filter(channel -> { if (id==null) { return channel.getParentId()==null; }else { return channel.getParentId()!=null&&channel.getParentId().equals(id); } }) .collect(Collectors.toList());
解析
为什么大于127就不行了呢? 因为java8内部的变量一般修饰符是final,而Integer可缓存的值是-128–127(详情查询源码729行)。为了解决此种问题可以使用equal取代==判断
附integer缓存源码
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }
阅读全文
1 0
- Java8集合filter过滤Integer数值为空问题解决方案
- 集合空过滤
- Java8中使用filter()过滤列表,使用collect将stream转化为list
- 异步调用webservice返回responseXML为空的问题解决方案
- java中ftpClient.listFiles()结果为空问题解决方案
- Java8<将Integer[]转换为int[]数组>
- int为空判断 -->Integer
- Java过滤掉map集合中key或value为空的值
- 通用工具类(过滤掉map集合中key或value为空的值)
- 配置Maven阿里云仓库和添加依赖时搜索为空问题解决方案
- 自定义Filter过滤集合中的元素
- CellType 属性为空 问题解决
- Java8 新特性之集合: removeIf(Predicate<? super E> filter)
- Java8新特性之集合removeIf(Predicate<? super E> filter)
- Integer.parser(String)返回值为空
- Integer 为空赋值给int
- struts2 判断集合为空
- 判断集合是否为空
- mysql之mysqldump——备份与还原
- 基于五种机器算法的信用风险评估
- Java swing 音乐播放器桌面歌词之字体变色
- 创建maven遇到web.xml is missing and <failOnMissingWebXml> is set to true错误
- 存放位置
- Java8集合filter过滤Integer数值为空问题解决方案
- GCD LCM
- nginx安装
- 选择排序算法java版
- 字符末尾添加其他符号
- ML之模型评估与选择简介
- android 根据生日生成星座
- 串口通信——写串口(C语言)
- hdu 2639 【01背包的第k个最优解】