Example usage for java.util.stream Collectors summingInt

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

Introduction

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

Prototype

public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper) 

Source Link

Document

Returns a Collector that produces the sum of a integer-valued function applied to the input elements.

Usage

From source file:Main.java

public static void main(String[] args) {
    Stream<String> s = Stream.of("1", "2", "3");

    int o = s.collect(Collectors.summingInt(n -> Integer.parseInt(n)));

    System.out.println(o);/*from   w  w  w.  j  a v a 2  s .c o  m*/
}

From source file:Main.java

public static void main(String... args) {
    int o = Food.menu.stream().collect(Collectors.summingInt(Food::getCalories));
    System.out.println(o);/*  www  . j a  v a  2 s.c o  m*/

}

From source file:Main.java

public static void main(String... args) {
    Map<Type, Integer> o = Food.menu.stream()
            .collect(Collectors.groupingBy(Food::getType, Collectors.summingInt(Food::getCalories)));

    System.out.println(o);/*  w ww .  j  av  a  2 s .  c  o m*/

}

From source file:net.thirdy.blackmarket.service.Ladder.java

public int size() {
    return ladderMapAllLeagues.entrySet().stream().map(es -> es.getValue().size())
            .collect(Collectors.summingInt(size -> size));
}

From source file:com.epam.ta.reportportal.core.widget.content.BugTrendChartContentLoader.java

/**
 * Calculate issues count for specified test item.<br>
 * Following series are supposed to be:<br>
 * - statistics.issueCounter.toInvestigate<br>
 * - statistics.issueCounter.productBugs<br>
 * - statistics.issueCounter.testBugs<br>
 * - statistics.issueCounter.systemIssues
 * //w w  w  .ja va2 s  .c o m
 * @param single
 * @return
 */
private static Integer getIssuesCount(ChartObject single) {
    return single.getValues().values().stream().collect(Collectors.summingInt(Integer::parseInt));
}

From source file:uk.co.jassoft.markets.api.SentimentController.java

@PreAuthorize("permitAll")
@RequestMapping(value = "company/{id}/story/{storyId}", method = RequestMethod.GET)
public @ResponseBody CompanyStorySentiment getCompanyStorySentiment(final HttpServletResponse response,
        @PathVariable String id, @PathVariable String storyId) throws UnknownHostException {
    List<StorySentiment> storySentiments = storySentimentRepository.findByCompany(id);

    Integer sentiment = null;/*from w w w .j  a  va  2s . co m*/

    // This can sometimes be null if the 1st story matched to a company hasnt yet been sentiment analysed
    if (storySentiments != null) {
        sentiment = storySentiments.stream()
                .map(storySentiment -> storySentiment.getEntitySentiment().stream()
                        .collect(Collectors.summingInt(EntitySentiment::getSentiment)))
                .collect(Collectors.summingInt(value -> value));
    }

    response.setHeader("Cache-Control", "max-age=" + CacheTimeout.TWENTY_FOUR_HOURS);
    return new CompanyStorySentiment(id, storyId, sentiment);
}

From source file:uk.co.jassoft.markets.api.SentimentController.java

@PreAuthorize("permitAll")
@RequestMapping(value = "company/{id}/period/{period}", method = RequestMethod.GET)
public @ResponseBody List<SentimentByDate> getSentimentsByCompany(final HttpServletResponse response,
        @PathVariable String id, @PathVariable PeriodType period) {

    // This could do some mongoDB magic to only select the StorySentiments in the date
    List<StorySentiment> storySentiments = storySentimentRepository.findByCompany(id);

    List<SentimentByDate> companySentiments = storySentiments.stream()
            .sorted((s1, s2) -> s1.getStoryDate().compareTo(s2.getStoryDate()))
            .map(storySentiment -> new SentimentByDate(id, storySentiment.getStoryDate(),
                    storySentiment.getEntitySentiment().stream()
                            .collect(Collectors.summingInt(value -> value.getSentiment()))))
            .collect(Collectors.groupingBy(
                    sentimentByDate -> getTrincatedDate(period, sentimentByDate.getDate()),
                    Collectors.summingInt(value1 -> value1.getSentiment())))
            .entrySet().stream()/*  w  w  w  .j  a  va2s .  com*/
            .map(dateIntegerEntry -> new SentimentByDate(id, dateIntegerEntry.getKey(),
                    dateIntegerEntry.getValue()))
            .sorted((o1, o2) -> o1.getDate().compareTo(o2.getDate())).collect(Collectors.toList());

    response.setHeader("Cache-Control", "max-age=" + CacheTimeout.FIFTEEN_MINUTES);
    return companySentiments;
}

From source file:org.perfcake.examples.weaver.Weaver.java

/**
 * Initializes the configuration.//  w  w  w  .ja va 2 s .  co m
 *
 * @throws IOException
 *       When it was not possible to parse the configuration.
 */
public void init() throws IOException {
    int maxThreads = Files.lines(Paths.get(config)).collect(Collectors.summingInt(this::parseWorker));
    if (threads > maxThreads || threads == 0) {
        if (threads > maxThreads) {
            log.warn("Maximum possible threads is " + maxThreads + ", while you requested " + threads
                    + ". Using " + maxThreads + ".");
        }
        threads = maxThreads;
    }

    if (shuffle) {
        log.info("Shuffling workers...");

        final List<Worker> workersList = workers.stream().collect(Collectors.toList());
        Collections.shuffle(workersList);
        workers.clear();
        workersList.forEach(workers::offer);
    }

    log.info("Creating executor with " + threads + " threads.");

    executor = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("worker-thread-%d").build());
}

From source file:org.trustedanalytics.metricsprovider.rest.MetricsDownloadTasks.java

public CompletableFuture<SpaceMetrics> getSpaceMetricsSingle(UUID space) {

    return getSpaceSummary(space).thenApply(response -> {

        Map<Boolean, List<CfApp>> apps = response.getApps().stream().collect(partitioningBy(CfApp::isStarted));

        int routesCount = response.getApps().stream().map(app -> app.getUrls().size())
                .collect(Collectors.summingInt(i -> i));

        int servicesCount = response.getServiceInstances().size();

        return new SpaceMetrics(apps.get(true).size(), apps.get(false).size(), routesCount, servicesCount);
    });//from w  ww .j  a v a 2s.c  om
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Map<MemberRegister, Integer> fetchTotalPointsPerMemberRegister(QuestionnaireType questionnaireType) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();
    Root<EvaluationAnswer> evaluationAnswer = cq.from(EvaluationAnswer.class);
    Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer);
    Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef
            .join(QuestionChoicesDef_.evaluationQuestionDef);
    ParameterExpression<QuestionnaireType> questionnaireTypeParam = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    Expression<Integer> value = evaluationAnswer.get(EvaluationAnswer_.answer).get(QuestionChoicesDef_.value)
            .as(Integer.class);
    cq.multiselect(evaluationAnswer.get(EvaluationAnswer_.memberRegister).alias("memberRegister"),
            value.alias("value"));
    cq.where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireTypeParam));
    TypedQuery<Tuple> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", questionnaireType);
    List<Tuple> result = query.getResultList();
    Map<MemberRegister, Integer> pointsPerMemberRegister = result.stream().collect(Collectors.groupingBy(t -> {
        return t.get("memberRegister", MemberRegister.class);
    }, Collectors.summingInt(t -> t.get("value", Integer.class))));

    return pointsPerMemberRegister;
}