title: Java 8: How to stream a list into a list of lists?
body: <p>Given a list of objects that need to be sorted and grouped:</p>
  
  <pre><code>static class Widget {
      // ...
      public String getCode() { return widgetCode; }
      public String getName() { return widgetName; }
  }
  
  List&lt;Widget&gt; widgetList = Arrays.asList(
      // several widgets with codes and names
  );
  </code></pre>
  
  <p>I want to group the list into a list-of-lists, grouped by <em>widgetCode</em>, with the elements of each sub-list in the order they were encountered in the original list.  I know that I can group them into a Map of lists using the <code>groupingBy</code> Collector:</p>
  
  <pre><code>Map&lt;String,List&lt;Widget&gt;&gt; widgetMap = widgetList.stream()
      .collect(groupingBy(Widget::getCode));
  </code></pre>
  
  <p>I do not take for granted that the keys are sorted, so I've taken the extra step of loading the whole thing into a SortedMap type:</p>
  
  <pre><code>SortedMap&lt;String,List&lt;Widget&gt;&gt; sortedWidgetMap = new TreeMap&lt;String,List&lt;Widget&gt;&gt;(
      widgetList.stream()
          .collect(groupingBy(Widget::getCode))
  );
  </code></pre>
  
  <p>I know I can get a Collection from <em>sortedWidgetMap</em> by using .values(), and I guess it is an ordered collection because it comes from an ordered map type, so that's my current solution:</p>
  
  <pre><code>Collection&lt;List&lt;Widget&gt;&gt; widgetListList = new TreeMap&lt;String,List&lt;Widget&gt;&gt;(
      widgetList.stream()
          .collect(groupingBy(Widget::getCode))
  ).values();
  widgetListList.forEach(System.out::println);  // do something with the data
  </code></pre>
  
  <p>This works so far, but I'm not confident that the resulting widgetListList is actually guaranteed to be in the right order (i.e. by <em>widgetCode</em>) or that the sub-lists will be built in the order they were found in the original list.  Also, I think it must be possible to use the Stream API alone to achieve the output I want.  So, how can I do this better?</p>