0

I've read many questions regarding Java 8 and Collections on this site and, given my limited understanding of java streams, I'm having some trouble trying to sort this Map. My code is as follows, being tradeList an ArrayList();

Map<String, Double> buyReport = tradeList.stream().filter(trade -> trade.getInstruction() == Instruction.BUY)
                .sorted(Comparator.comparing(trade -> trade.getInstructionDate()))
                .collect(Collectors.groupingBy(trade -> dateFormat.format(trade.getInstructionDate()),
                        Collectors.summingDouble(trade -> trade.getUSDAmount())));

Does it make any sense to include the .sorted() statement when composing a HashMap? I tried to create a LinkedHashmap, use a custom comparator for the value i need the object instances to compare (a Double), but to no avail.

I can include any other piece of code you may find useful.

Thanks in advance!!

Update: tried this recently; still getting results unordered when grouping by company code and then summing company totals:

Map<String, Double> entityOutgoingReport = tradeList.stream()
                .filter(trade -> trade.getInstruction() == Instruction.SELL)
                .collect(Collectors.groupingBy(trade -> String.valueOf(trade.getEntity()),
                        LinkedHashMap::new,
                        Collectors.summingDouble(trade -> trade.getUSDAmount())));

for (String entity : entityOutgoingReport.keySet()) {
            String key = entity;
            String value = decFormat.format(entityOutgoingReport.get(entity));
            tableBuilder.addRow(key, value); //Just pretty printing to console
        }
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Juan M
  • 4,063
  • 4
  • 19
  • 28

1 Answers1

0

Simply supply a LinkedHashMap into which the results will be inserted therefore maintaining order.

.collect(Collectors.groupingBy(trade -> 
       dateFormat.format(trade.getInstructionDate()),
                LinkedHashMap::new,
                    Collectors.summingDouble(trade -> trade.getUSDAmount())));

Full code:

Map<String, Double> entityOutgoingReport = 
      tradeList.stream()
               .filter(trade -> trade.getInstruction() == Instruction.SELL)
               .sorted(Comparator.comparing(trade -> trade.getInstructionDate()))
               .collect(Collectors.groupingBy(trade -> String.valueOf(trade.getEntity()),
                        LinkedHashMap::new,
                        Collectors.summingDouble(trade -> trade.getUSDAmount())));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126