title: Categorize ArrayList of objects based on their property
body: <p>I have an ArrayList of Products, and each Product has a category as a property (so each category can have many products). I just need to format the data so that the products are categorized according to the category property. </p>
  
  <p>I would think that a HashMap would be useful, as I could just use the category as the key and the ArrayList of products as the value.</p>
  
  <p>If this is the correct approach, can someone assist me with the logic involved in turning my ArrayList into the HashMap as I have described? Or maybe there is a better way of handling it.</p>
  
  <p>/** Update **/</p>
  
  <p>Here is a sample method, but I'm not exactly sure how to make the logic happen:</p>
  
  <pre><code>private HashMap&lt;String, ArrayList&gt; sortProductsByCategory (ArrayList&lt;Product&gt; productList) {
  
      // The hashmap value will be the category name, and the value will be the array of products
      HashMap&lt;String, ArrayList&gt; 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;
  
      }
  
  
  }
  </code></pre>