【问题标题】:Copying specified objects from one ArrayList to another将指定对象从一个 ArrayList 复制到另一个
【发布时间】:2015-04-04 03:39:42
【问题描述】:

我目前有一个 ArrayList 保存“产品”对象,每个对象中都包含一个字符串、整数和双精度值。 我希望能够使用参数搜索对象,找出与搜索参数匹配的 ID(整数值)并将该对象复制到另一个 ArrayList 中。是否可以通过 Iterator 来做到这一点,还是有更简单的方法来做到这一点?

【问题讨论】:

    标签: java arraylist iterator


    【解决方案1】:

    简单的方法是使用 Java 8 流:

    List<Product> filtered = 
       prods.stream().filter(p -> p.getId() == targetId).collect(toList());
    

    假设import static java.util.stream.Collectors.toList;

    【讨论】:

      【解决方案2】:

      Java 少 8 版的简单直接解决方案:

      ArrayList<Product> arrOriginal = new ArrayList<Product>(); //with values of yours
      
      ArrayList<Product> arrCopy = new ArrayList<Product>(); //empty
      
      for (Product item : arrOriginal){
          if (<some condition>){
              arrCopy.add(item);
          }
      
      }
      

      【讨论】:

        【解决方案3】:
        ArrayList<Product> arrListOriginal = new ArrayList<Product>();
        arrListOriginal.add(item1);
        arrListOriginal.add(item2);
        arrListOriginal.add(item3);
        
        ArrayList<Product> arrListCopy = new ArrayList<Product>();
        Product objProduct = new Product();
        for (int index=0;index<arrListOriginal.size();index++){
            objProduct = (Product) arrListOriginal.get(index);
            if (<search condition with objProduct>){
                arrListCopy.add(objProduct);
            }
        }
        

        【讨论】:

        • 不会让我有“Product objProduct = new Product(); 因为我的构造函数中有参数,以创建具有 ID、描述和价格的对象。
        猜你喜欢
        • 2020-10-24
        • 2011-02-07
        • 2012-06-30
        • 2017-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-15
        相关资源
        最近更新 更多