2013-07-21 151 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

是的,這是絕對有效的方法你想從「一維」視圖切換到「二維」。

相關問題