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

Java技术求助:实现Producer名称匹配筛选并排序(禁用Stream)

解决方案

要实现筛选匹配用户输入的Producer元素并排序的需求,我们可以分成两步完成:先手动筛选符合条件的元素,再用你已有的Comparator对结果排序,全程不使用Stream。

步骤1:修改筛选+排序方法

更新你的getItemByProducer方法,让它接收用户输入的关键词,先筛选再排序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class YourClassName { // 替换成实际的类名
    public static List<Clothing> getItemByProducer(String userInput) {
        // 1. 初始化存储匹配结果的列表
        List<Clothing> matchedClothes = new ArrayList<>();
        
        // 处理空输入的边界情况(可选)
        if (userInput == null || userInput.trim().isEmpty()) {
            // 若输入为空,返回所有元素排序后的结果
            List<Clothing> allSorted = new ArrayList<>(Items.clothingItemList);
            Collections.sort(allSorted, new SortByProducersComparator());
            return allSorted;
        }
        
        // 2. 手动遍历原列表,筛选匹配Producer名称的元素
        String inputKeyword = userInput.trim();
        for (Clothing item : Items.clothingItemList) {
            // 判断Producer名称是否包含输入的关键词(支持部分匹配)
            // 若需要忽略大小写,改为:item.getProducers().getName().toLowerCase().contains(inputKeyword.toLowerCase())
            if (item.getProducers().getName().contains(inputKeyword)) {
                matchedClothes.add(item);
            }
        }
        
        // 3. 对筛选结果按Producer名称排序
        Collections.sort(matchedClothes, new SortByProducersComparator());
        
        // 打印结果并返回
        System.out.println(matchedClothes);
        return matchedClothes;
    }
}

步骤2:修正SortByProducersComparator泛型

确保你的比较器泛型与实际处理的Clothing对象一致(如果Clothing继承自Items,原写法也能运行,但更精准的泛型会减少潜在错误):

import java.util.Comparator;

public class SortByProducersComparator implements Comparator<Clothing> {
    @Override
    public int compare(Clothing o1, Clothing o2) {
        // 直接获取Producer的名称进行字典序比较
        String producerName1 = o1.getProducers().getName();
        String producerName2 = o2.getProducers().getName();
        return producerName1.compareTo(producerName2);
    }
}

步骤3:调用示例

在主方法中模拟用户输入并调用:

public static void main(String[] args) {
    // 模拟用户输入,比如输入"Ja"会匹配Jack和Jari
    String userInput = "Ja";
    List<Clothing> result = getItemByProducer(userInput);
}

关键说明

  • 筛选逻辑:通过手动遍历Items.clothingItemList,判断每个Clothing的Producer名称是否包含用户输入的关键词,完全符合禁止使用Stream的要求。
  • 排序逻辑:复用你已有的Comparator实现,对筛选后的列表进行排序,满足仅使用Comparator的要求。
  • 边界处理:加入了空输入的判断,避免出现异常,你可以根据实际需求调整这部分逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:05:17