You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中基于分类关联的宠物类型过滤产品列表实现咨询

解决方案

核心逻辑步骤

  1. 构建分类ID映射:将prdctCtgrList转换为以分类ID为键的哈希表/对象,快速通过分类ID获取对应分类的pet_type信息,避免重复遍历分类列表。
  2. 筛选目标分类ID:根据选中的pet_type,找出所有包含该宠物类型的分类ID,形成一个集合。
  3. 过滤产品列表:遍历产品列表,仅保留所属分类ID在目标集合中的产品。

代码示例(JavaScript)

// 1. 构建分类ID映射(预处理一次即可)
const categoryMap = prdctCtgrList.data.reduce((map, category) => {
  map[category.id] = category;
  return map;
}, {});

// 2. 根据选中的pet_type获取目标分类ID集合
function getTargetCategoryIds(selectedPetType) {
  return Object.values(categoryMap)
    .filter(category => category.pet_type.some(pet => pet.type === selectedPetType))
    .map(category => category.id);
}

// 3. 过滤产品列表
function filterProductsByPetType(selectedPetType) {
  const targetCategoryIds = getTargetCategoryIds(selectedPetType);
  return prdctList.data.filter(product => targetCategoryIds.includes(product.product_category.id));
}

// 调用示例
const catProducts = filterProductsByPetType('Cat'); // 返回product 1和product 2
const dogProducts = filterProductsByPetType('Dog'); // 返回product 2

代码示例(Java)

import java.util.*;
import java.util.stream.Collectors;

// 假设已定义ProductModel和PrdctCtgrModel实体类
public class ProductFilter {
    public static List<ProductModel> filterByPetType(List<ProductModel> prdctList, List<PrdctCtgrModel> prdctCtgrList, String selectedPetType) {
        // 1. 构建分类ID映射
        Map<Integer, PrdctCtgrModel> categoryMap = prdctCtgrList.stream()
                .collect(Collectors.toMap(PrdctCtgrModel::getId, category -> category));

        // 2. 获取目标分类ID集合
        Set<Integer> targetCategoryIds = categoryMap.values().stream()
                .filter(category -> category.getPetType().stream()
                        .anyMatch(pet -> pet.getType().equals(selectedPetType)))
                .map(PrdctCtgrModel::getId)
                .collect(Collectors.toSet());

        // 3. 过滤产品列表
        return prdctList.stream()
                .filter(product -> targetCategoryIds.contains(product.getProductCategory().getId()))
                .collect(Collectors.toList());
    }
}

逻辑说明

  • 预处理分类映射能大幅提升多轮过滤的性能,尤其是分类数据量较大时。
  • 使用some()(JS)或anyMatch()(Java)快速判断分类是否包含目标宠物类型。
  • 通过分类ID集合匹配产品,实现精准过滤,完全符合示例中的需求。

内容的提问来源于stack exchange,提问作者Dimas Satrya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 06:37:46