我有一个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