2015-08-20 48 views
-1

我想將產品分類到與其類別關聯的集合中作爲關鍵字。我不知道如何做到這一點。看來我的代碼不斷將所有產品添加到同一組中。如何使用指向集合的密鑰創建映射

代碼我到目前爲止:

//創建新的地圖

public class ProductList implements ProductListInterface { 
static Collection<Product> productList = new TreeSet<Product>(); 
private Map<String, Set<Product>> productCategory = new HashMap<>(); 


public void filter(){ 

    for (Product item: productList){ 
     String key = item.getCategory(); 
    if (productCategory.containsKey(key)){ 
     Set<Product> set = productCategory.get(key); 
     set.add(item); 
     productCategory.put(key, set); 


     }else{ 
    Set<Product> productSet = new HashSet<Product>(); 
    productSet.add(item); 
    productCategory.put(key, productSet); 

     } 


    } 


} 

//然後檢索與集合類關鍵

public Collection<Product> getFilter(String category){ 
    return productCategory.get(category); 

} 
+0

此代碼有效。問題在別的地方。 –

回答

1

嘗試像這個:

public void filter(){ 

    for (Product item: productList){ 
     String key = item.getCategory(); 

     if(productCategory.get(key) == null){ 
      Set<Product> productSet = new HashSet<Product>(); 
      productCategory.put(key, productSet); 
     } 

     Set<Product> set = productCategory.get(key); 
     set.add(item); 
     productCategory.put(key, set); 
    } 

} 

它應該工作,如果沒有,嘗試調試key

1

這是另一種方式,雖然我運行你的代碼,它也很好。也許問題在別的地方。

Collection<Product> productList = . . . 
Map<String,Set<Product>> map = 
     productList.stream() 
     .collect(Collectors.groupingBy(Product::getCategory, 
       Collectors.toSet())); 
0

我弗雷德里科同意你的代碼的工作,但你並不需要重複自己,你不需要把組回地圖。

for (Product item : productList) { 
    String key = item.getCategory(); 
    Set<Product> set = productCategory.get(key); 
    if (set == null) { 
     set = new HashSet<>(); 
     productCategory.put(key, set); 
    } 
    set.add(item); 
} 

自認爲是一個非常共同模式,你甚至可以壓縮的碼位。

for (Product item : productList) { 
    String key = item.getCategory(); 
    Set<Product> set = productCategory.get(key); 
    if (set == null) 
     productCategory.put(key, set = new HashSet<>()); 
    set.add(item); 
}