stream流使用filter函数避免使用==判断等值

有关于Integer缓存池的问题,读者可自行搜索。简要来说,Integer的-128至127之间的值都是存储在栈中,而其他值存储在堆中。


private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
     List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
         //在这里使用了==判断
         return categoryEntity.getParentCid()==root.getCatId();
     }).collect(Collectors.toList());
     return children;
}

在做电商项目的时候,通过遍历一二三级树型目录时,用到了这样一个判断:

categoryEntity.getParentCid()==root.getCatId();

原本的目的是想过滤掉那些父节点id不相等的结果,然而CatId大于127,而Integer中-128到127之外的值都是引用对象,所以==号无法判断相等,导致filter过滤后的值都没能录入,这里应当使用equals判断。

categoryEntity.getParentCid().equals(root.getCatId());


版权声明:本文为ldm54466183原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。