Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用收集器进行分组_Java_Mongodb - Fatal编程技术网

Java 如何使用收集器进行分组

Java 如何使用收集器进行分组,java,mongodb,Java,Mongodb,我从MongoDB数据库中检索数据,并在每次将JSONObject添加到列表后将其存储在JSONObject中,以便通过使用收集器(按日期)创建组。我确信group by的代码运行正常,因为我在一个简单的示例中对其进行了测试,但问题是我有此显示 while (traficCursor.hasNext()) { try { DBObject next = traficCursor.next(); wordsArray = next.

我从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();
    }

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

jsonObject = new JSONObject();

如果不这样做,您将使用最新插入的对象值和data.add(jsonObject)更新
数据的每个条目
;应该在环内还是环外?在环内,这样很好
jsonObject = new JSONObject();