如何优雅的过滤List对象并获取筛选后的的对象集合

文章简介:

本文主要说明在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;

	/**
	 * 分类id
	 */
	@TableId
	private Long catId;
	/**
	 * 分类名称
	 */
	private String name;
	/**
	 * 父分类id
	 */
	private Long parentCid;
	/**
	 * 层级
	 */
	private Integer catLevel;
	/**
	 * 是否显示[0-不显示,1显示]
	 */
	private Integer showStatus;
	/**
	 * 排序
	 */
	private Integer sort;
	/**
	 * 图标地址
	 */
	private String icon;
	/**
	 * 计量单位
	 */
	private String productUnit;
	/**
	 * 商品数量
	 */
	private Integer productCount;

}

目的要求:

获取到父分类id==0的数据

public void demo() {
        //查出所有数据
        List<CategoryEntity> list = baseMapper.selectList(null);

        //普通版
        List<CategoryEntity> newList1 = new ArrayList<>();
        for (CategoryEntity entity : list) {
            if (entity.getParentCid() == 0) {
                newList1.add(entity);
            }
        }

        //优雅版
        List<CategoryEntity> newList2 = list.stream()
                .filter((categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        })).collect(Collectors.toList());

    }
经验分享 程序员 微信小程序 职场和发展