gpt4 book ai didi

java - 如何使用收集器进行分组

转载 作者:行者123 更新时间:2023-12-02 09:50:59 26 4
gpt4 key购买 nike

我从 MongoDB 数据库检索数据,并在每次将 JSONObject 添加到列表后将它们存储在 JSONObject 中,以便使用收集器(按日期)进行分组,我确信代码自从我在一个简单的示例中测试它们以来,group by 运行正确,但问题是我有这个显示

 while (traficCursor.hasNext()) {
try {
DBObject next = traficCursor.next();
wordsArray = next.get("Date").toString().split("\\s+");
jsonObject.put("DateComplete",wordsArray[0]);
jsonObject.put("Heure",wordsArray[1]);
for (String mapKeyInfo : next.keySet()) {
jsonObject.put(mapKeyInfo,next.get(mapKeyInfo));
}
data.add(jsonObject);

}
catch (Exception e) {
e.printStackTrace();
}
}
try {
Map<Object, List<JSONObject>> groupbydate = data.stream()
.map(json -> new AbstractMap.SimpleEntry<>(json.getString("Date"), json))
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
groupbydate.entrySet().forEach(gbd -> System.out.println(gbd.getValue()));
} catch (Exception e) {
e.printStackTrace();
}

[{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","借方":"61","Heure":"18:00","日期":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","借方":"61","Heure":"18:00","日期":"2018年1月24日18:00"},{"id_arc_trafic":“1”,“taux”:“1360”,“DateComplete”:“24/01/2018”,“_id”:“5ce66598a4021f9e6224c699”,“借记”:“61”,“Heure”:“18:00” ,"日期":"2018年1月24日 18:00"}]这是重复自身的 JSONObject 的最后一行

这就是我想要的按日期分组,我按属性日期分组显示记录

[{"id_arc_trafic":"1","taux":"100","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"250","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"1360","DateComplete":"25/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"500","DateComplete":"27/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"140","Heure":"18:00","Date":"27/01/2018 18:00"}]

最佳答案

jsonObject 应该在 while 循环内初始化:

jsonObject = new JSONObject();

如果您不这样做,您将使用最新插入的对象的值更新data的每个条目

关于java - 如何使用收集器进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56324594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com