title: Java parallel stream: how to wait for threads for a parallel stream to finish?
body: <p>So I have a list from which I obtain a parallel stream to fill out a map, as follows:</p>
  
  <pre><code>Map&lt;Integer, TreeNode&gt; map = new HashMap&lt;&gt;();
  List&lt;NodeData&gt; list = some_filled_list;
  
  //Putting data from the list into the map
  list.parallelStream().forEach(d -&gt; {
                  TreeNode node = new TreeNode(d);
                  map.put(node.getId(), node);
              });
  
  //print out map
  map.entrySet().stream().forEach(entry -&gt; {
       System.out.println("Processing node with ID = " + entry.getValue().getId());
                  });
  </code></pre>
  
  <p>The problem with this code is that the map is being printed out when the "putting data" process is still going on (cuz it's parallel), so as a result, map has not yet received all the elements from the list yet. Of course, in my real code, it is not just printing out the map; I use a map to take advantage of O(1) lookup time.</p>
  
  <p>My question is:</p>
  
  <ol>
  <li><p>how to make the main thread wait so that the "putting data" is finished before the map is printed out? I tried to put the "putting data" inside a thread t, and do <code>t.start()</code> and <code>t.join()</code>, but that doesn't help.</p></li>
  <li><p>Maybe I am not supposed to use parallel stream in this case? The list is long, and I just want to take advantage of the parallelism to improve efficiency.</p></li>
  </ol>