如何使用引用一组的键创建一个Map

时间:2015-08-20 01:48:54

标签: java collections set

我想将产品分类为与其类别相关联的集合作为关键字。我不知道该怎么做。似乎我的代码将所有产品添加到同一组中。

我到目前为止的代码:

//创建新地图

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);

 }

3 个答案:

答案 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 :(得分:1)

这是另一种方式,虽然我运行了你的代码,它也很好。也许问题出在其他地方。

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

答案 2 :(得分: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);
}
相关问题