如何使用收集器进行分组

阿卢卢·瓦格迪

我从 MongoDB 数据库中检索数据,并在每次将 JSONObject 添加到列表后将它们存储在 JSONObject 中,以便通过使用收集器(按日期)创建组我确定组的代码是运行正常,因为我在一个简单的例子中测试了它们,但问题是我有这个显示

 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","debit":"61","Heure": "18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018" ,"_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1 ","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date ":"24/01/2018 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使用最新插入的对象的值更新每个条目

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章