如何使用收集器进行分组

时间:2019-05-27 10:48:44

标签: java mongodb

我每次从一个MongoDB数据库中检索数据,然后将JSONObject添加到一个列表中,然后将它们存储在一个JSONObject中,以便通过使用Collector进行分组(按日期),我确定因为我在一个简单的示例中对其进行了测试,所以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“,” Date“:” 24/01/2018 18:00“},{” id_arc_trafic“:” 1“,” taux“:” 1360“,” DateComplete“:” 24/01 / 2018“,” _ id“:” 5ce66598a4021f9e6224c699“,”借记“:” 61“,” Heure“:” 18:00“,” Date“:” 24/01/2018 18:00“},{” id_arc_trafic“ :“ 1”,“ taux”:“ 1360”,“ DateComplete”:“ 24/01/2018”,“ _ id”:“ 5ce66598a4021f9e6224c699”,“借记”:“ 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"}]

1 个答案:

答案 0 :(得分:1)

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

jsonObject = new JSONObject();

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