【问题标题】:Spliting ArrayList into several ArrayLists based on variable根据变量将 ArrayList 拆分为多个 ArrayList
【发布时间】:2014-12-29 09:40:56
【问题描述】:

我需要根据这个 ArrayList 中的一个变量,将一个包含原始数据类型、String 和 ArrayLists 的 ArrayList 拆分为几个 ArrayList。

我的 ArrayList purchaseOrderList 具有字符串类型的“品牌”等等。我想将这个 ArrayList 拆分为尽可能多的新 ArrayList,因为我有不同的品牌。不管我怎么做,我总是陷入无限循环。

ArrayList<Brand> brandList = new ArrayList<Brand>();

brandList.add(new Brand(purchaseOrderList.get(0).getBrand()));
for (int i = 0; i < brandList.size(); i++) {
    for (Item item : purchaseOrderList) {
        if (brandList.get(i).getBrand().equals(item.getBrand())) {
            brandList.get(i).setItemList(item); //Add the items from the purchaseOrderList
        } else {
            brandList.add(new Brand(item.getBrand()));
        }
    }
}

有什么建议吗?

【问题讨论】:

  • 另外,在上面的示例中,List 中只有一个 Brand
  • 不使用地图就不行吗?
  • 你害怕地图吗?
  • 我正在使用 GWT,我认为使用 ArrayList 来完成我正在做的事情会更容易。

标签: java arraylist


【解决方案1】:

您有一个无限循环,因为您想遍历数组的所有元素,但同时又添加了新元素。

您应该使用:int arraySize = brandList.size(); 并在第一个中使用它的值,如下所示:for (int i = 0; i &lt; arraySize; i++)

这样你将遍历brandList数组开头的所有元素, 我想这就是你想要做的。

【讨论】:

    【解决方案2】:

    对于此类问题,您可能应该使用地图:

    Map<Brand, ArrayList<Item>> map = new HashMap<Brand, ArrayList<Item>>();
    
    
    for(Item item : purchaseOrderList){
      if(map.get(item.getBrand()) == null)
        map.put(item.getBrand(), new ArrayList<Item>());
      else 
        map.get(item.getBrand()).add(item);
    }
    

    【讨论】:

    • 谢谢。易于实施。现在我希望这能在我的 GWT 项目中正常工作。
    猜你喜欢
    • 2014-08-17
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多