我有一個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;
}
}
你想打印他們的方式,或將它們存儲的地方呀? –
你的方法聽起來很合理。向我們展示您想要創建「HashMap」的代碼,並告訴我們您遇到了什麼問題。 – Jeffrey
[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