代码之家  ›  专栏  ›  技术社区  ›  Juan M

Java 8映射未按值正确排序[重复]

  •  0
  • Juan M  · 技术社区  · 6 年前

    我在这个网站上阅读了许多关于Java 8和集合的问题,鉴于我对Java流的理解有限,我在尝试对这个地图进行排序时遇到了一些困难。 我的代码如下,是tradeList和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())));
    

    包含有任何意义吗。撰写HashMap时的sorted()语句?我试图创建一个LinkedHashmap,使用一个自定义比较器来比较需要对象实例比较的值(一个双精度值),但没有效果。

    我可以包含您可能觉得有用的任何其他代码。

    提前谢谢!!

    更新:最近尝试过;按公司代码分组,然后对公司总数求和时,仍会得到无序的结果:

    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
            }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ousmane D.    6 年前

    只需提供 LinkedHashMap 将结果插入其中,从而保持秩序。

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

    完整代码:

    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())));