【问题标题】:Searching a multi column array list? [closed]搜索多列数组列表? [关闭]
【发布时间】:2019-08-31 11:51:04
【问题描述】:

我有一个 CountryModel 类,其中包含两列名称和代码,我的问题是我不知道如何在此进行预测搜索。

假设我想搜索国家名称是“Aruba”的位置,因为我有像 getName()这样的方法

ArrayList<CountryModel> countries = new ArrayList<>();
countries.add(new CountryModel("Afghanistan", "93"));
countries.add(new CountryModel("Australia", "61"));
countries.add(new CountryModel("Aruba", "297"));

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

【问题讨论】:

  • 搜索什么?一个完整的CountryModel 对象、一个名称、一个值,还是别的什么?
  • 我想在其中一个对象中搜索一个国家的名称
  • 即使你把我的问题搁置,我已经得到了答案,我很高兴可以去。感谢那些提供答案的人

标签: java arraylist


【解决方案1】:

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

for (int i = 0; i < countries.size(); I++) {
    if (countries.get(i).getTitle().equals ("Afghanistan")) {
    }
}

【讨论】:

  • 感谢您的回答,因为我现在已经得到了我真正需要的东西
【解决方案2】:

在 Streaming API 之前(以防万一你不能使用流(java8))

for (CountryModel l1 : l) {
    if ("Aruba".equalsIgnoreCase(l1.getName())) {
        System.out.println("Found!!");
        break;
    }
}

从 Java 8 开始: 在你的情况下,收集到一个列表并不是很简单,因为很难相信,你可以拥有多个同名的国家,因此,

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

【讨论】:

    【解决方案3】:

    一个带有 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();
        }
    

    也可以更新为流式传输,但在没有更多上下文的情况下并没有真正有用

    【讨论】:

      【解决方案4】:

      你可以在这里使用一个流:

      List<CountryModel> countries = new ArrayList<>();
      // populate list
      
      List<CountryModel> matches = countries.stream()
                  .filter(c -> "Afghanistan".equals(c.getName())
                  .collect(Collectors.toList());
      

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

      【讨论】:

        猜你喜欢
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 2015-07-06
        • 1970-01-01
        相关资源
        最近更新 更多