Example usage for java.util.stream Collectors counting

List of usage examples for java.util.stream Collectors counting

Introduction

In this page you can find the example usage for java.util.stream Collectors counting.

Prototype

public static <T> Collector<T, ?, Long> counting() 

Source Link

Document

Returns a Collector accepting elements of type T that counts the number of input elements.

Usage

From source file:hr.diskobolos.service.impl.EvaluationAnswerServiceImpl.java

@Override
public RankingAndCategorizationOfSportsDto fetchRankingAndCategorizationOfSportsByMemberRegisterAndQuestionnaireType(
        MemberRegister memberRegister, QuestionnaireType questionnaireType) {
    RankingAndCategorizationOfSportsDto rankingAndCategorizationOfSportsDto = new RankingAndCategorizationOfSportsDto();
    rankingAndCategorizationOfSportsDto.setId(memberRegister.getId());
    rankingAndCategorizationOfSportsDto.setName(memberRegister.getName());

    List<EvaluationAnswer> evaluationAnswers = evaluationAnswerPersistence
            .findAllByMemberRegisterAndQuestionnaireType(memberRegister, questionnaireType);
    Integer totalPoints = 0;/* w ww .j  a  v  a  2 s .c o  m*/

    if (!evaluationAnswers.isEmpty()) {

        totalPoints = evaluationAnswers.stream().mapToInt(e -> Integer.valueOf(e.getAnswer().getValue())).sum();

        evaluationAnswers.forEach((EvaluationAnswer e) -> {
            EvaluationQuestionnaireDefEnum question = e.getAnswer().getEvaluationQuestionDef().getQuestion();
            switch (question) {
            case THE_CRITERION_OF_SPORT_DEVELOPMENT_INTERNATIONAL_FEDERATION:
                rankingAndCategorizationOfSportsDto
                        .setCriterionOfSportInternationalFederation(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case THE_CRITERION_OF_SPORT_DEVELOPMENT_NATIONAL_ALLIANCE:
                rankingAndCategorizationOfSportsDto
                        .setCriterionOfSportNationalAlliance(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case THE_CRITERION_OF_SPORT_DEVELOPMENT_COUNTY_ALLIANCE:
                rankingAndCategorizationOfSportsDto
                        .setCriterionOfSportCountyAlliance(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case THE_CRITERION_OF_SPORT_DEVELOPMENT_CITY_OF_ZADAR:
                rankingAndCategorizationOfSportsDto
                        .setCriterionOfSportCityOfZadar(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case PUBLIC_INTEREST_OF_SPORT_PUBLIC_INTEREST:
                rankingAndCategorizationOfSportsDto
                        .setSportStatusOfPublicInterest(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case PUBLIC_INTEREST_OF_SPORT_TOWN_ZADAR:
                rankingAndCategorizationOfSportsDto
                        .setSportStatusTownZadar(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case PUBLIC_INTEREST_OF_SPORT_OLYMPIC_STATUS:
                rankingAndCategorizationOfSportsDto
                        .setOlympicSportsStatus(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case PUBLIC_INTEREST_OF_SPORT_IMPORTANCE_FOR_TEACHING_TZK:
                rankingAndCategorizationOfSportsDto
                        .setImportanceForTeachingTzk(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case SPORTS_QUALITY_NUMBER_CATEGORIZED_ATHLETES:
                rankingAndCategorizationOfSportsDto
                        .setSportsQualityNumberOfCategorizedAthletes(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case SPORTS_QUALITY_ACHIEVED_SPORTS_RESULTS_IN_CROATIA:
                rankingAndCategorizationOfSportsDto.setSportsQualityAccomplishedSportsResultsCroatia(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            case SPORTS_QUALITY_ACHIEVED_SPORTS_RESULTS_IN_TOWN_ZADAR:
                rankingAndCategorizationOfSportsDto.setSportsQualityAccomplishedSportsResultsTownOfZadar(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            default:
                break;
            }
        });
    }

    List<EvaluationQuestionnaireDefEnum> questionnaireDef = Arrays
            .asList(EvaluationQuestionnaireDefEnum.values());
    Long numberOfQuestion = questionnaireDef.stream().filter(
            q -> q.getQuestionnaireType().equals(QuestionnaireType.RANKING_AND_CATEGORIZATION_OF_SPORTS))
            .collect(Collectors.counting());
    rankingAndCategorizationOfSportsDto.setQuestionnairePercentage(
            getQuestionnairePercentage(evaluationAnswers, numberOfQuestion, questionnaireDef));

    rankingAndCategorizationOfSportsDto.setTotalPoints(totalPoints);

    return rankingAndCategorizationOfSportsDto;
}

From source file:com.github.horrorho.liquiddonkey.cloud.Looter.java

void snapshot(HttpClient client, Core core, HttpAgent agent, Backup backup, int id)
        throws BadDataException, IOException, InterruptedException {

    boolean toReport = config.debug().toReport();
    Path path = config.file().base().resolve(backup.backupUDID()).resolve(config.file().reportsDirectory());
    Predicate<ICloud.MBSFile> nonUndecryptableFilter = file -> !file.getAttributes().hasEncryptionKey()
            || backup.keyBagManager().fileKey(file) != null;

    // Retrieve file list.
    int limit = config.client().listLimit();
    Snapshot snapshot = agent//  www .  ja  v  a 2 s  .c  o m
            .execute((c, mmeAuthToken) -> Snapshots.from(c, core, mmeAuthToken, backup, id, limit));

    if (snapshot == null) {
        logger.warn("-- snapshot() > snapshot not found: {}", id);
        return;
    }
    ICloud.MBSSnapshotAttributes attr = snapshot.mbsSnapshot().getAttributes();
    logger.info("-- snapshot() > files: {}", snapshot.filesCount());
    std.println();
    std.println(
            "Retrieving snapshot: " + id + " (" + attr.getDeviceName() + " " + attr.getProductVersion() + ")");

    // Total files.
    std.println("Files(total): " + snapshot.filesCount());
    if (toReport) {
        csvWriter.files(sorted(snapshot), path.resolve("snapshot_" + id + "_files.csv"));
    }

    // Mode summary.
    Map<Mode, Long> modes = snapshot.files().stream()
            .collect(Collectors.groupingBy(Mode::mode, Collectors.counting()));
    logger.info("-- snapshot() > modes: {}", modes);

    // Non-empty files filter.
    snapshot = Snapshots.from(snapshot, file -> file.getSize() != 0 && file.hasSignature());
    logger.info("-- snapshot() > filtered non empty, remaining: {}", snapshot.filesCount());
    std.println("Files(non-empty): " + snapshot.filesCount());

    // User filter
    snapshot = Snapshots.from(snapshot, filter);
    logger.info("-- snapshot() > filtered configured, remaining: {}", snapshot.filesCount());
    std.println("Files(filtered): " + snapshot.filesCount());
    if (toReport) {
        csvWriter.files(sorted(snapshot), path.resolve("snapshot_" + id + "_filtered.csv"));
    }

    // Undecryptable filter
    Snapshot undecryptable = Snapshots.from(snapshot, nonUndecryptableFilter.negate());
    snapshot = Snapshots.from(snapshot, nonUndecryptableFilter);
    logger.info("-- snapshot() > filtered undecryptable, remaining: {}", snapshot.filesCount());
    std.println("Files(non-undecryptable): " + snapshot.filesCount());

    // Dump undecryptables
    //        Map<ICloud.MBSFile, Outcome> undecryptableOutcomes = undecryptables.stream()
    //                .collect(Collectors.toMap(Function.identity(), file -> Outcome.FAILED_DECRYPT_NO_KEY));
    //        outcomesConsumer.accept(undecryptableOutcomes);
    if (toReport) {
        csvWriter.files(sorted(undecryptable), path.resolve("snapshot_" + id + "_undecryptable.csv"));
    }

    // Local filter
    if (config.engine().toForceOverwrite()) {
        logger.debug("-- snapshot() > forced overwrite");
    } else {
        long a = System.currentTimeMillis();
        snapshot = LocalFileFilter.from(snapshot, config.file()).apply(snapshot);
        long b = System.currentTimeMillis();
        logger.info("-- snapshot() > filtered local, remaining: {} delay(ms): {}", snapshot.filesCount(),
                b - a);
        std.println("Files(non-local): " + snapshot.filesCount());
    }

    if (snapshot.filesCount() == 0) {
        return;
    }

    // Retrieve
    Outcomes outcomes = Outcomes.create();
    OutcomesProgressPercentage progress = OutcomesProgressPercentage.from(snapshot, std);
    Consumer<Map<ICloud.MBSFile, Outcome>> outcomesConsumer = outcomes.andThen(progress);
    std.println();
    std.println("Retrieving: " + Bytes.humanize(progress.totalBytes()));

    // Fetch files
    SnapshotDownloader.from(config.engine(), config.file()).download(agent, core, snapshot, outcomesConsumer);

    std.println();
    std.println("Completed:");
    outcomes.print(std);
    std.println();
}

From source file:com.mycompany.wolf.Room.java

private void notifyWitchSave() {
    ScheduledFuture[] holder = new ScheduledFuture[1];
    holder[0] = scheduledExecutorService.schedule(() -> {
        holder[0].cancel(true);/*  ww  w.ja  v  a2 s.  c o  m*/
        notifyHunterKillIfDead();
    }, WITCH_SAVE_DURATION, TimeUnit.MILLISECONDS);

    /*
     *  
     */
    List<Map.Entry<String, Long>> top2 = wolfVotings.values().stream()
            .collect(Collectors.groupingBy(wolfVoting -> wolfVoting.playerId, Collectors.counting())).entrySet()
            .stream()
            .sorted(Comparator.comparingLong((Map.Entry<String, Long> entry) -> entry.getValue()).reversed())
            .limit(2).collect(Collectors.toList());
    if (top2.size() == 1 || (top2.size() > 1 && top2.get(0).getValue().compareTo(top2.get(1).getValue()) > 0)) {
        theVoted = top2.get(0).getKey();
    } else if (top2.size() > 1) {
        theVoted = top2.get(0).getKey();
    } else {
        List<String> undead = sessions.stream()
                .filter(session -> !WOLF.equals(session.getUserProperties().get("role")))
                .map(session -> getPlayerId(session)).filter(((Predicate<String>) dead::contains).negate())
                .collect(Collectors.toList());
        theVoted = undead.get(new Random().nextInt(undead.size()));
    }
    newlyDead.add(theVoted);

    /*
     * ? 
     */
    witchPoisonings.values().stream().map(witchPoisoning -> witchPoisoning.playerId).forEach(newlyDead::add);

    Map<String, Object> notifyWolfVoted = ImmutableMap.of("code", "notifyWolfVoted", "properties",
            ImmutableMap.of("playerId", theVoted));
    String jsonText = JsonUtils.toString(notifyWolfVoted);
    sessions.stream().forEach(s -> {
        s.getAsyncRemote().sendText(jsonText);
    });
}

From source file:hr.diskobolos.service.impl.EvaluationAnswerServiceImpl.java

@Override
public CategorizationOfSportsPerSportClubDto fetchCategorizationOfSportsPerSportClubByMemberRegisterAndQuestionnaireType(
        MemberRegister memberRegister, QuestionnaireType questionnaireType) {
    CategorizationOfSportsPerSportClubDto categorizationOfSportsPerSportClubDto = new CategorizationOfSportsPerSportClubDto();
    categorizationOfSportsPerSportClubDto.setId(memberRegister.getId());
    categorizationOfSportsPerSportClubDto.setName(memberRegister.getName());

    List<EvaluationAnswer> evaluationAnswers = evaluationAnswerPersistence
            .findAllByMemberRegisterAndQuestionnaireType(memberRegister, questionnaireType);
    Integer totalPoints = 0;/*from w w w.j av  a2 s  .c om*/

    if (!evaluationAnswers.isEmpty()) {

        totalPoints = evaluationAnswers.stream().mapToInt(e -> Integer.valueOf(e.getAnswer().getValue())).sum();

        evaluationAnswers.forEach((EvaluationAnswer e) -> {
            EvaluationQuestionnaireDefEnum question = e.getAnswer().getEvaluationQuestionDef().getQuestion();
            switch (question) {
            case CATEGORIZATION_ACCORDING_TO_NUMBER_OF_REGISTERED_CLUBS_IN_NATIONAL_FEDERATION:
                categorizationOfSportsPerSportClubDto
                        .setCategorizationOnNationalFederationLevel(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_BY_TYPE_OF_SPORT:
                categorizationOfSportsPerSportClubDto
                        .setCategorizationOnSportTypeLevel(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_AGE_CATEGORIES:
                categorizationOfSportsPerSportClubDto
                        .setCategorizationAccordingToAge(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_RANK_OF_COMPETITION_SYSTEM:
                categorizationOfSportsPerSportClubDto
                        .setCategorizationOnCompetitionSystemLevel(Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_NUMBER_OF_TEAM_MEMBERS_COMPETING:
                categorizationOfSportsPerSportClubDto.setCategorizationBasedOnNumberOfTeamMembersCompeting(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_MASS_IN_SPORTS_SCHOOLS:
                categorizationOfSportsPerSportClubDto.setCategorizationAccordingToMassInSportsSchools(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_PROFESSIONAL_STAFF:
                categorizationOfSportsPerSportClubDto.setCategorizationAccordingToProfessionalStaff(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            case CATEGORIZATION_ACCORDING_TO_TRADITION_OF_TOWN_ZADAR:
                categorizationOfSportsPerSportClubDto.setCategorizationAccordingToTraditionOfTownZadar(
                        Integer.valueOf(e.getAnswer().getValue()));
                break;
            case COFFICIENCY_OF_SPORTS_CATEGORY:
                categorizationOfSportsPerSportClubDto
                        .setCofficiencyOfSportsCategory(Integer.valueOf(e.getAnswer().getValue()));
                break;
            default:
                break;
            }
        });
    }

    List<EvaluationQuestionnaireDefEnum> questionnaireDef = Arrays
            .asList(EvaluationQuestionnaireDefEnum.values());
    Long numberOfQuestion = questionnaireDef.stream().filter(
            q -> q.getQuestionnaireType().equals(QuestionnaireType.CATEGORIZATION_OF_SPORTS_PER_SPORT_CLUB))
            .collect(Collectors.counting());
    categorizationOfSportsPerSportClubDto.setQuestionnairePercentage(
            getQuestionnairePercentage(evaluationAnswers, numberOfQuestion, questionnaireDef));

    categorizationOfSportsPerSportClubDto.setTotalPoints(totalPoints);

    return categorizationOfSportsPerSportClubDto;
}

From source file:hr.diskobolos.service.impl.EvaluationAnswerServiceImpl.java

private Float getQuestionnairePercentage(List<EvaluationAnswer> evaluationAnswers, Long numberOfQuestion,
        List<EvaluationQuestionnaireDefEnum> questionnaireDef) {
    Long numberOfAnsweredQuestions = evaluationAnswers.stream()
            .filter(e -> questionnaireDef.contains(e.getAnswer().getEvaluationQuestionDef().getQuestion()))
            .collect(Collectors.counting());
    Float questionnairePercentage = ((float) numberOfAnsweredQuestions / numberOfQuestion) * 100;
    return new BigDecimal(Float.toString(questionnairePercentage)).setScale(2, BigDecimal.ROUND_HALF_UP)
            .floatValue();/*from w w w.j  a va2 s . c  o m*/
}

From source file:ws.salient.session.Session.java

public Map<String, Long> getFactCount() {
    return ksession.getFactHandles().stream().map((handle) -> {
        return ksession.getObject(handle);
    }).collect(Collectors.groupingBy((o) -> {
        return o.getClass().getSimpleName();
    }, Collectors.counting()));
}

From source file:com.mycompany.wolf.Room.java

private void notifySomeoneBeVoted() {
    Collection<String> newlyDead = new LinkedHashSet<>();

    List<Map.Entry<String, Long>> top2 = playerVotings.values().stream()
            .collect(Collectors.groupingBy(playerVoting -> playerVoting.playerId, Collectors.counting()))
            .entrySet().stream()//from w  w  w.j ava 2  s  . co m
            .sorted(Comparator.comparingLong((Map.Entry<String, Long> entry) -> entry.getValue()).reversed())
            .limit(2).collect(Collectors.toList());
    if (top2.size() == 1
            || (top2.size() == 2 && top2.get(0).getValue().compareTo(top2.get(1).getValue()) > 0)) {
        newlyDead.add(top2.get(0).getKey());
        this.dead.add(top2.get(0).getKey());

        if (sessions.stream().noneMatch(session -> WOLF.equals(session.getUserProperties().get("role")))) {
            wolvesLose();
        }
    }

    Map<String, Object> notifyDead = ImmutableMap.of("code", "notifyDead", "properties", newlyDead);
    String jsonText = JsonUtils.toString(notifyDead);
    sessions.stream().forEach(s -> s.getAsyncRemote().sendText(jsonText));

    notifyWolvesKillVillagers();
}

From source file:com.ggvaidya.scinames.model.Dataset.java

public String getExplicitChangesCountSummary(Project p) {
    if (getExplicitChanges(p).count() == 0)
        return "None";

    Map<ChangeType, Long> changeCounts = getExplicitChanges(p)
            .collect(Collectors.groupingBy(Change::getType, Collectors.counting()));

    String changes_by_type = changeCounts.entrySet().stream()
            .sorted((a, b) -> b.getValue().compareTo(a.getValue())).map(e -> e.getValue() + " " + e.getKey())
            .collect(Collectors.joining(", "));

    return getExplicitChanges(p).count() + " explicit changes (" + changes_by_type + ")";
}

From source file:com.ggvaidya.scinames.model.Dataset.java

public String getImplicitChangesCountSummary(Project p) {
    if (getImplicitChanges(p).count() == 0)
        return "None";

    Map<ChangeType, Long> implicitChangeCounts = getImplicitChanges(p)
            .collect(Collectors.groupingBy(Change::getType, Collectors.counting()));

    String implicit_changes_by_type = implicitChangeCounts.entrySet().stream()
            .sorted((a, b) -> b.getValue().compareTo(a.getValue())).map(e -> e.getValue() + " " + e.getKey())
            .collect(Collectors.joining(", "));

    return getImplicitChanges(p).count() + " implicit changes (" + implicit_changes_by_type + ")";
}