Java 搜索多列数组列表?

Java 搜索多列数组列表?,java,arraylist,Java,Arraylist,我有一个类CountryModel,它的名称和代码中有两列,我的问题是我不知道如何在这个程序中搜索 假设我想搜索国家名为“Aruba”的地方,因为我得到了类似于getName() ArrayList countries=new ArrayList(); 添加(新的CountryModel(“阿富汗”,“93”)); 添加(新的CountryModel(“澳大利亚”、“61”)); 添加(新的CountryModel(“阿鲁巴”、“297”); 当然,我知道如何使用contains()函数搜索单

我有一个类CountryModel,它的名称和代码中有两列,我的问题是我不知道如何在这个程序中搜索

假设我想搜索国家名为“Aruba”的地方,因为我得到了类似于getName()

ArrayList countries=new ArrayList();
添加(新的CountryModel(“阿富汗”,“93”));
添加(新的CountryModel(“澳大利亚”、“61”));
添加(新的CountryModel(“阿鲁巴”、“297”);

当然,我知道如何使用contains()函数搜索单个列,但对我来说,这已成为一项艰巨的任务。

您可以在此处使用流:

List<CountryModel> countries = new ArrayList<>();
// populate list

List<CountryModel> matches = countries.stream()
            .filter(c -> "Afghanistan".equals(c.getName())
            .collect(Collectors.toList());
List countries=new ArrayList();
//填充列表
列表匹配项=countries.stream()
.filter(c->“阿富汗”.equals(c.getName())
.collect(Collectors.toList());

理想情况下,我们希望重载
CountryModel
equals()
方法,但对于您的搜索案例,您并不是在寻找整个对象,而是某个对象的属性。因此,以某种方式迭代列表可能是这里的唯一选项。

一个简单的循环,其中包含if语句,可以轻松解决您的问题

public static void main(String... args){
       ArrayList<CountryModel> countries = new ArrayList<>();
       countries.add(new CountryModel("Afghanistan", "93"));
       countries.add(new CountryModel("Australia", "61"));
       countries.add(new CountryModel("Aruba", "297"));

       searchLoop(countries, "Aruba", "297");
   }

    private static Optional<CountryModel> searchLoop(ArrayList<CountryModel> countries, String name, String code) {
        for(CountryModel model : countries){
            if(model.getName().equals(name) && model.getCode().equals(code)){
                return Optional.of(model);
            }
        }
        return Optional.empty();
    }
publicstaticvoidmain(字符串…参数){
ArrayList国家/地区=新的ArrayList();
添加(新的CountryModel(“阿富汗”,“93”));
添加(新的CountryModel(“澳大利亚”、“61”));
添加(新的CountryModel(“阿鲁巴”、“297”);
searchLoop(国家,“阿鲁巴”、“297”);
}
私有静态可选searchLoop(ArrayList国家/地区、字符串名称、字符串代码){
适用于(国家/地区模型:国家/地区){
if(model.getName().equals(name)和&model.getCode().equals(code)){
返回可选。of(型号);
}
}
返回可选的.empty();
}
也可以更新为流,但在流API之前,如果没有更多的上下文,就无法真正使用流(以防万一您不能使用流(java8))

自java 8以来: 在你的例子中,收集到一个列表并不太正式,因为很难相信,你可以有多个国家同名,因此

CountryModel matches = l.stream()
     .filter(c -> "Aruba".equalsIgnoreCase(c.getName()))
     .findAny()
     .orElse(null);      

这应该对您有所帮助,因为它不使用其他人建议的流API,因为您可以针对较低的API,例如16

for (int i = 0; i < countries.size(); I++) {
    if (countries.get(i).getTitle().equals ("Afghanistan")) {
    }
}
for(int i=0;i
搜索什么?一个完整的
CountryModel
对象,一个名称,一个值,等等?我想在其中一个对象中搜索一个国家的名称。如果你搁置我的问题,我已经得到了我的答案,我很乐意去。感谢那些提供答案的人感谢他们的回答,因为我现在已经得到了我真正需要的答案
CountryModel matches = l.stream()
     .filter(c -> "Aruba".equalsIgnoreCase(c.getName()))
     .findAny()
     .orElse(null);      
for (int i = 0; i < countries.size(); I++) {
    if (countries.get(i).getTitle().equals ("Afghanistan")) {
    }
}