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

Java:如何通过产品名称包含匹配从ArrayList查找Product对象

ArrayList按产品名称包含匹配查找对象的解决方案

问题原因

你的代码中al.contains(name)无法正确工作,核心问题有两个:

  1. ArrayList<Product>存储的是Product对象,contains方法默认使用Object.equals()比较,传入String类型和Product对象永远不相等,因此永远返回false。
  2. 需求是名称包含匹配,而非完全相等,即使传入Product对象,默认的equals也只比较对象引用,无法满足需求。

解决方案1:遍历集合逐个匹配

直接遍历ArrayList,检查每个Product的name是否包含输入的字符串(支持忽略大小写匹配):

import java.util.*;

class Product {
    String name;
    int price;
    int id;
    Product(int i, String name, int price) {
        this.id = i;
        this.name = name;
        this.price = price;
    }
}

public class Test{
    public static void main(String[] args) {
        ArrayList<Product> al = new ArrayList<Product>();
        al.add(new Product(1, "Samsung", 10000));
        al.add(new Product(2, "Apple", 20000));
        al.add(new Product(3, "Nokia", 30000));
        al.add(new Product(4, "Sony", 40000));
        al.add(new Product(5, "LG", 50000));
        
        for (Product p : al) {
            System.out.println(p.id + " " + p.name + " " + p.price);
        }
        
        System.out.println("Enter the name of the product to search:");
        Scanner sc = new Scanner(System.in);
        String searchName = sc.nextLine().trim();
        
        boolean found = false;
        List<Product> matchedProducts = new ArrayList<>();
        // 遍历集合,检查名称包含匹配,忽略大小写
        for (Product p : al) {
            if (p.name.toLowerCase().contains(searchName.toLowerCase())) {
                matchedProducts.add(p);
                found = true;
            }
        }
        
        if (found) {
            System.out.println("匹配的产品:");
            for (Product p : matchedProducts) {
                System.out.println(p.id + " " + p.name + " " + p.price);
            }
        } else {
            System.out.println("未找到匹配的产品");
        }
        
        sc.close();
    }
}

解决方案2:使用Java 8+ Stream API简化代码

如果使用Java 8及以上版本,可以用Stream API更简洁地实现筛选:

// 替换原代码中的查找逻辑部分
import java.util.stream.Collectors;

String searchName = sc.nextLine().trim();
List<Product> matchedProducts = al.stream()
    .filter(p -> p.name.toLowerCase().contains(searchName.toLowerCase()))
    .collect(Collectors.toList());

if (!matchedProducts.isEmpty()) {
    System.out.println("匹配的产品:");
    matchedProducts.forEach(p -> System.out.println(p.id + " " + p.name + " " + p.price));
} else {
    System.out.println("未找到匹配的产品");
}

关键注意点

  • 若需要严格区分大小写的包含匹配,去掉代码中的toLowerCase()调用即可。
  • 不要依赖ArrayList.contains()实现自定义匹配逻辑,该方法仅适用于对象的相等性判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:50:23