Java8集合filter过滤Integer数值为空问题解决方案

问题描述

项目使用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() {}
    }
    原文作者:石奈子
    原文地址: https://blog.csdn.net/u014042066/article/details/76246608
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞