2013-07-21 155 views
0

我有一个ArrayList的产品,每个产品都有一个属性类别(因此每个类别都可以有很多产品)。我只需要格式化数据,以便根据类别属性对产品进行分类。根据对象的属性对对象ArrayList进行分类

我会认为HashMap会很有用,因为我可以使用类别作为键和产品的ArrayList作为值。

如果这是正确的方法,有人可以帮助我把我的ArrayList变成HashMap的逻辑,正如我所描述的那样?或者也许有更好的方法来处理它。

/** **更新/

下面是一个简单的方法,但我不完全知道如何使逻辑发生:

private HashMap<String, ArrayList> sortProductsByCategory (ArrayList<Product> productList) { 

    // The hashmap value will be the category name, and the value will be the array of products 
    HashMap<String, ArrayList> map; 

    for(Product product: productList) { 

     // If the key does not exist in the hashmap 
     if(!map.containsKey(product.getCategory()) { 
      // Add a key to the map, add product to new arraylist 
     } 
     else { 
      // add the product to the arraylist that corresponds to the key 
     } 
     return map; 

    } 


} 
+0

你想打印他们的方式,或将它们存储的地方呀? –

+4

你的方法听起来很合理。向我们展示您想要创建“HashMap”的代码,并告诉我们您遇到了什么问题。 – Jeffrey

+0

[Apache Commons JXPath](http://commons.apache.org/proper/commons-jxpath/)或[Guava Predicate](http://google-collections.googlecode.com/svn/trunk/javadoc/com/) google/common/base/Predicate.html)可能! – NINCOMPOOP

回答

0

可能会做的更好的方式,但它似乎为我工作:

private HashMap<String, ArrayList<Product>> sortProductsByCategory (ArrayList<Product> arrayList) { 

    HashMap<String, ArrayList<Product>> map = new HashMap<String, ArrayList<Product>>(); 

    for(Product product: arrayList) { 

     // If the key does not exist in the hashmap 
     if(!map.containsKey(product.getCategory().getName())) { 
      ArrayList<Product> listInHash = new ArrayList<Product>(); 
      listInHash.add(product); 
      map.put(product.getCategory().getName(), listInHash); 
     } else { 
      // add the product to the arraylist that corresponds to the key 
      ArrayList<Product> listInHash = map.get(product.getCategory().getName()); 
      listInHash.add(product); 

     } 

    } 

    return map; 

} 
0

是的,这是绝对有效的方法你想从“一维”视图切换到“二维”。

相关问题