com.tengen.Week3Homework1Stream.java Source code

Java tutorial

Introduction

Here is the source code for com.tengen.Week3Homework1Stream.java

Source

/*
 * Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.tengen;

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Week3Homework1Stream {
    public static void main(String[] args) throws UnknownHostException {
        MongoClient client = new MongoClient();

        DB database = client.getDB("school");
        DBCollection collection = database.getCollection("students");

        try (DBCursor students = collection.find()) {
            students.forEach(student -> {
                BasicDBList scores = (BasicDBList) student.get("scores");
                DBObject worstHomeScoreDoc = scores.stream().map(o -> (DBObject) o) // cast Object to DBObject
                        .filter(o -> o.get("type").equals("homework"))
                        .min((o1, o2) -> ((Double) o1.get("score")).compareTo((Double) o2.get("score"))).get();
                scores.remove(worstHomeScoreDoc);

                collection.update(new BasicDBObject("_id", student.get("_id")), student);
            });
        }
    }
}