title: optimizing java 8 stream operations
body: <p>So I was trying to optimize my code as much as possible. The following code used to run on 5,something seconds, however I managed to reduce it to about 1,4 seconds, however it's still not enough. What can I do to optimize this code even more? (Maybe I should mention that the times I talked about happen when the aux Map ends up with 170080 keys).</p>
  
  <pre><code>    public List&lt;String&gt; getProdutosMaisCompradosQuantidade(int filial, int X){
      Map&lt;String, ProdutoFilial&gt; aux;
  
      if(filial==0) {
          aux = new HashMap&lt;&gt;(ValoresFixos.CATALOGO_PRODUTOS_TAMANHO_INICIAL);
          filiais.stream()
                 .forEach( (f) -&gt; {
                      Map&lt;String, ProdutoFilial&gt; aux2 = f.getMapProdutosDadosFilialSemEncapsulamento();
                      aux2.forEach((k,t) -&gt; {
                              if(t.getQuantidade()&gt;0){
                                  if(aux.containsKey(k)) aux.get(k).atualizarValores(t);
                                  else aux.put(k,t);
                              }
                      });
                  });
      }
      else aux = filiais.get(filial-1).getMapProdutosDadosFilialSemEncapsulamento();
  
      List&lt;String&gt; list = 
         aux
         .entrySet()
         .stream()
         .sorted(new ComparadorProdutoQuantidade())
         .map(e -&gt; e.getKey()+"\n     |   o Quantidade: "+e.getValue().getQuantidade()+"; Comprado por "+e.getValue().getNumeroCompradores()+" Clientes Distintos")
         .collect(Collectors.toList());
  
      if(X&gt;list.size()) X = list.size();
      list.subList(X, list.size()).clear();
  
      return list;
  
  }
  </code></pre>
  
  <p>All the methods I use here are almost O(1) complexity and the comparator isn't too taxing either so that shouldn't be the problem, is there something I may not know that could help me optimize this stream operations? Maybe the entrySet I use can be avoided...? Because it's probably the most expensive operation here...</p>
  
  <p>EDIT1: Maybe I should explain the idea behind this method. It's main purpose is to order the map aux and return a list with the keys ordered (the keys are also modified but that's not the main intention)</p>