本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象并获取筛选后对象集合,stream()方法下还有许多遍历的方法,本篇文章只是使用到 .filter() 以做到抛砖引玉的作用
模拟数据: 数据库数据: 对应的java实体:package com.luck.bookstore.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Long catId;
private String name;
private Long parentCid;
private Integer catLevel;
private Integer showStatus;
private Integer sort;
private String icon;
private String productUnit;
private Integer productCount;
}
目的要求:
获取到父分类id==0的数据
public void demo() {
//查出所有数据
List list = baseMapper.selectList(null);
//普通版
List newList1 = new ArrayList<>();
for (CategoryEntity entity : list) {
if (entity.getParentCid() == 0) {
newList1.add(entity);
}
}
//优雅版
List newList2 = list.stream()
.filter((categoryEntity -> {
return categoryEntity.getParentCid() == 0;
})).collect(Collectors.toList());
}



