Example usage for java.util.stream Collectors groupingBy

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

Introduction

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

Prototype

public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier) 

Source Link

Document

Returns a Collector implementing a "group by" operation on input elements of type T , grouping elements according to a classification function, and returning the results in a Map .

Usage

From source file:com.github.sevntu.checkstyle.ordering.MethodOrder.java

public int getAccessorsSplitCases() {
    return currentOrdering.stream().filter(method -> method.isGetter() || method.isSetter())
            .collect(Collectors.groupingBy(Method::getAccessiblePropertyName)).values().stream()
            .collect(Collectors.summingInt(this::getMethodGroupSplitCount));
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl.DocumentChartDataManagerImpl.java

@Override
public void createDocumentHistoryPartyChart(final AbstractOrderedLayout content, final String org) {
    final DataSeries dataSeries = new DataSeries();
    final Series series = new Series();

    final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> allMap = getViewRiksdagenPartyDocumentDailySummaryMap();

    final List<ViewRiksdagenPartyDocumentDailySummary> itemList = allMap
            .get(org.toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING).trim());

    if (itemList != null) {

        final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> map = itemList.parallelStream()
                .filter(t -> t != null).collect(Collectors.groupingBy(
                        t -> StringUtils.defaultIfBlank(t.getEmbeddedId().getDocumentType(), NO_INFO)));

        addDocumentHistoryByPartyData(dataSeries, series, map);
    }/*  ww w.j  a v  a 2  s .  c  o m*/

    addChart(content, "Document history party", new DCharts().setDataSeries(dataSeries)
            .setOptions(chartOptions.createOptionsXYDateFloatLegendOutside(series)).show());
}

From source file:io.syndesis.project.converter.DefaultProjectGenerator.java

@SuppressWarnings("PMD.UnusedPrivateMethod") // PMD false positive
private byte[] generateFlowYaml(TarArchiveOutputStream tos, GenerateProjectRequest request)
        throws JsonProcessingException {
    final Map<Step, String> connectorIdMap = new HashMap<>();
    final List<? extends Step> steps = request.getIntegration().getSteps();
    final Flow flow = new Flow();

    if (!steps.isEmpty()) {
        // Determine connector prefix
        request.getIntegration().getSteps().stream().filter(s -> s.getStepKind().equals(Endpoint.KIND))
                .filter(s -> s.getAction().isPresent()).filter(s -> s.getConnection().isPresent())
                .collect(Collectors.groupingBy(s -> s.getAction().get().getCamelConnectorPrefix()))
                .forEach((prefix, stepList) -> {
                    if (stepList.size() > 1) {
                        for (int i = 0; i < stepList.size(); i++) {
                            connectorIdMap.put(stepList.get(i), Integer.toString(i + 1));
                        }//from ww  w .  j a v a 2s .  com
                    }
                });

        Queue<Step> remaining = new LinkedList<>(steps);
        Step first = remaining.remove();
        if (first != null) {
            GeneratorContext generatorContext = new GeneratorContext.Builder()
                    .connectorCatalog(connectorCatalog).generatorProperties(generatorProperties)
                    .request(request).tarArchiveOutputStream(tos).flow(flow).visitorFactoryRegistry(registry)
                    .build();

            StepVisitorContext stepContext = new StepVisitorContext.Builder().index(1).step(first)
                    .remaining(remaining)
                    .connectorIdSupplier(step -> Optional.ofNullable(connectorIdMap.get(step))).build();

            visitStep(generatorContext, stepContext);
        }
    }

    SyndesisModel syndesisModel = new SyndesisModel();
    syndesisModel.addFlow(flow);

    return YAML_OBJECT_MAPPER.writeValueAsBytes(syndesisModel);
}

From source file:com.hurence.logisland.connect.source.KafkaConnectStreamSource.java

@Override
public Dataset<Row> getBatch(Option<Offset> start, Offset end) {
    Long startOff = start.isDefined() ? Long.parseLong(start.get().json())
            : !bufferedRecords.isEmpty() ? bufferedRecords.firstKey() : 0L;

    Map<Integer, List<InternalRow>> current = new LinkedHashMap<>(
            bufferedRecords.subMap(startOff, Long.parseLong(end.json()) + 1)).keySet().stream()
                    .flatMap(offset -> {
                        List<Tuple2<SourceTask, SourceRecord>> srl = bufferedRecords.remove(offset);
                        if (srl != null) {
                            uncommittedRecords.put(offset, srl);
                            return srl.stream();
                        }//ww w.  jav a2s.c  om
                        return Stream.empty();
                    }).map(Tuple2::_2).map(
                            sourceRecord -> InternalRow.fromSeq(JavaConversions
                                    .<Object>asScalaBuffer(Arrays.asList(toUTFString(sourceRecord.topic()),
                                            toUTFString(sourceRecord.sourcePartition()),
                                            toUTFString(sourceRecord.sourceOffset()),
                                            keyConverter.fromConnectData(sourceRecord.topic(),
                                                    sourceRecord.keySchema(), sourceRecord.key()),
                                            valueConverter.fromConnectData(sourceRecord.topic(),
                                                    sourceRecord.valueSchema(), sourceRecord.value())))
                                    .toSeq()))
                    .collect(Collectors.groupingBy(row -> Objects.hashCode((row.getString(1)))));
    return sparkPlatform.createStreamingDataFrame(sqlContext, new SimpleRDD(sqlContext.sparkContext(), current),
            DATA_SCHEMA);

}

From source file:org.obiba.mica.search.CoverageQueryExecutor.java

/**
 * For a taxonomy {@link Vocabulary}, report the number of hits and optionally the
 * number of hits for each bucket.//w w w  .  java  2s. c o  m
 */
private int addVocabularyCoverage(MicaSearch.TaxonomyCoverageDto.Builder taxoBuilder, Taxonomy taxonomy,
        Vocabulary vocabulary, Map<String, Integer> hits, @Nullable List<BucketResult> bucketResults,
        Map<String, Map<String, MicaSearch.TermsAggregationResultDto>> aggTermsTitlesMap) {
    int sumOfHits = 0;
    if (vocabulary.hasTerms()) {
        Map<String, List<BucketResult>> bucketResultsByTerm = bucketResults == null ? Maps.newHashMap()
                : bucketResults.stream().collect(Collectors.groupingBy(BucketResult::getTerm));

        MicaSearch.VocabularyCoverageDto.Builder vocBuilder = MicaSearch.VocabularyCoverageDto.newBuilder();
        vocBuilder.setVocabulary(dtos.asDto(vocabulary, getLocale()));
        vocabulary.getTerms().stream().filter(term -> applyFilter(taxonomy, vocabulary, term))
                .forEach(term -> addTermCoverage(vocBuilder, term, hits,
                        bucketResultsByTerm.get(term.getName()), aggTermsTitlesMap));
        // only one term can be applied at a time, then the sum of the term hits is the number of variables
        // that cover this vocabulary
        sumOfHits = hits == null ? 0 : hits.values().stream().mapToInt(x -> x).sum();
        vocBuilder.setHits(sumOfHits);

        if (!vocabulary.isRepeatable()) {
            vocBuilder.setCount(sumOfHits);
        }

        // compute the sum of the hits for all terms per bucket
        if (bucketResults != null) {
            Map<String, List<BucketResult>> bucketResultsByBucketField = bucketResults.stream()
                    .collect(Collectors.groupingBy(BucketResult::getBucketField));

            bucketResultsByBucketField.keySet().forEach(field -> {
                Map<String, List<BucketResult>> bucketResultsByBucketValue = bucketResultsByBucketField
                        .get(field).stream().collect(Collectors.groupingBy(BucketResult::getBucketValue));

                bucketResultsByBucketValue.keySet().stream().sorted().forEach(value -> {
                    List<BucketResult> buckets = bucketResultsByBucketValue.get(value);
                    int sumOfBucketHits = buckets.stream().mapToInt(BucketResult::getHits).sum();
                    if (sumOfBucketHits > 0) {
                        MicaSearch.BucketCoverageDto.Builder builder = getBucketCoverageDtoBuilder(field, value,
                                sumOfBucketHits, aggTermsTitlesMap.get(field).get(value));

                        if (!vocabulary.isRepeatable())
                            builder.setCount(builder.getHits());

                        vocBuilder.addBuckets(builder);
                    }
                });
            });
        }
        if (!vocBuilder.getTermsList().isEmpty()) {
            taxoBuilder.addVocabularies(vocBuilder);
        } else {
            sumOfHits = 0;
        }
    }

    return sumOfHits;
}

From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java

private Map<String, List<WebResource>> readVariableResources() throws IOException {

    try (InputStream is = new ClassPathResource(this.webResourcesConfigName).getInputStream()) {
        Constructor constructor = new Constructor(VariableConfig.class);
        Yaml yaml = new Yaml(constructor);
        return StreamSupport.stream(yaml.loadAll(is).spliterator(), false).map(e -> (VariableConfig) e)
                .map(this::createWebResources).flatMap(wr -> wr.stream())
                .collect(Collectors.groupingBy(WebResource::getVarName));
    }/*from  w  w  w .jav a2s . c o  m*/
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/book", method = RequestMethod.GET)
public String showPaymentPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        //paypal related parameters
        @RequestParam(value = "paymentId", required = false) String paypalPaymentId,
        @RequestParam(value = "PayerID", required = false) String paypalPayerID,
        @RequestParam(value = "paypal-success", required = false) Boolean isPaypalSuccess,
        @RequestParam(value = "paypal-error", required = false) Boolean isPaypalError,
        @RequestParam(value = "fullName", required = false) String fullName,
        @RequestParam(value = "firstName", required = false) String firstName,
        @RequestParam(value = "lastName", required = false) String lastName,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "billingAddress", required = false) String billingAddress,
        @RequestParam(value = "hmac", required = false) String hmac,
        @RequestParam(value = "postponeAssignment", required = false) Boolean postponeAssignment, Model model,
        Locale locale) {// w ww. j  av  a  2s.  co m

    return eventRepository.findOptionalByShortName(eventName)
            .map(event -> ticketReservationManager.findById(reservationId).map(reservation -> {

                if (reservation.getStatus() != TicketReservationStatus.PENDING) {
                    return redirectReservation(Optional.of(reservation), eventName, reservationId);
                }

                List<Ticket> ticketsInReservation = ticketReservationManager
                        .findTicketsInReservation(reservationId);
                if (Boolean.TRUE.equals(isPaypalSuccess) && paypalPayerID != null && paypalPaymentId != null) {
                    model.addAttribute("paypalPaymentId", paypalPaymentId)
                            .addAttribute("paypalPayerID", paypalPayerID)
                            .addAttribute("paypalCheckoutConfirmation", true).addAttribute("fullName", fullName)
                            .addAttribute("firstName", firstName).addAttribute("lastName", lastName)
                            .addAttribute("email", email).addAttribute("billingAddress", billingAddress)
                            .addAttribute("hmac", hmac)
                            .addAttribute("postponeAssignment", Boolean.TRUE.equals(postponeAssignment))
                            .addAttribute("showPostpone", Boolean.TRUE.equals(postponeAssignment));
                } else {
                    model.addAttribute("paypalCheckoutConfirmation", false)
                            .addAttribute("postponeAssignment", false)
                            .addAttribute("showPostpone", ticketsInReservation.size() > 1);
                }

                try {
                    model.addAttribute("delayForOfflinePayment", Math.max(1, TicketReservationManager
                            .getOfflinePaymentWaitingPeriod(event, configurationManager)));
                } catch (TicketReservationManager.OfflinePaymentException e) {
                    if (event.getAllowedPaymentProxies().contains(PaymentProxy.OFFLINE)) {
                        log.error("Already started event {} has been found with OFFLINE payment enabled",
                                event.getDisplayName(), e);
                    }
                    model.addAttribute("delayForOfflinePayment", 0);
                }

                OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId,
                        event, locale);
                List<PaymentProxy> activePaymentMethods = paymentManager
                        .getPaymentMethods(event.getOrganizationId()).stream()
                        .filter(p -> TicketReservationManager.isValidPaymentMethod(p, event,
                                configurationManager))
                        .map(PaymentManager.PaymentMethod::getPaymentProxy).collect(toList());

                if (orderSummary.getFree() || activePaymentMethods.stream()
                        .anyMatch(p -> p == PaymentProxy.OFFLINE || p == PaymentProxy.ON_SITE)) {
                    boolean captchaForOfflinePaymentEnabled = configurationManager
                            .isRecaptchaForOfflinePaymentEnabled(event);
                    model.addAttribute("captchaRequestedForOffline", captchaForOfflinePaymentEnabled)
                            .addAttribute("recaptchaApiKey",
                                    configurationManager.getStringConfigValue(
                                            Configuration.getSystemConfiguration(RECAPTCHA_API_KEY), null))
                            .addAttribute("captchaRequestedFreeOfCharge",
                                    orderSummary.getFree() && captchaForOfflinePaymentEnabled);
                }

                boolean invoiceAllowed = configurationManager.hasAllConfigurationsForInvoice(event)
                        || vatChecker.isVatCheckingEnabledFor(event.getOrganizationId());
                PaymentForm paymentForm = PaymentForm.fromExistingReservation(reservation);
                model.addAttribute("multiplePaymentMethods", activePaymentMethods.size() > 1)
                        .addAttribute("orderSummary", orderSummary).addAttribute("reservationId", reservationId)
                        .addAttribute("reservation", reservation)
                        .addAttribute("pageTitle", "reservation-page.header.title").addAttribute("event", event)
                        .addAttribute("activePaymentMethods", activePaymentMethods)
                        .addAttribute("expressCheckoutEnabled", isExpressCheckoutEnabled(event, orderSummary))
                        .addAttribute("useFirstAndLastName", event.mustUseFirstAndLastName())
                        .addAttribute("countries", TicketHelper.getLocalizedCountries(locale))
                        .addAttribute("euCountries",
                                TicketHelper.getLocalizedEUCountries(locale,
                                        configurationManager.getRequiredValue(
                                                getSystemConfiguration(ConfigurationKeys.EU_COUNTRIES_LIST))))
                        .addAttribute("euVatCheckingEnabled",
                                vatChecker.isVatCheckingEnabledFor(event.getOrganizationId()))
                        .addAttribute("invoiceIsAllowed", invoiceAllowed)
                        .addAttribute("vatNrIsLinked",
                                orderSummary.isVatExempt() || paymentForm.getHasVatCountryCode())
                        .addAttribute("billingAddressLabel", invoiceAllowed ? "reservation-page.billing-address"
                                : "reservation-page.receipt-address");

                boolean includeStripe = !orderSummary.getFree()
                        && activePaymentMethods.contains(PaymentProxy.STRIPE);
                model.addAttribute("includeStripe", includeStripe);
                if (includeStripe) {
                    model.addAttribute("stripe_p_key", paymentManager.getStripePublicKey(event));
                }
                Map<String, Object> modelMap = model.asMap();
                modelMap.putIfAbsent("paymentForm", paymentForm);
                modelMap.putIfAbsent("hasErrors", false);

                boolean hasPaidSupplement = ticketReservationManager.hasPaidSupplements(reservationId);
                model.addAttribute("ticketsByCategory", ticketsInReservation.stream()
                        .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream().map((e) -> {
                            TicketCategory category = eventManager.getTicketCategoryById(e.getKey(),
                                    event.getId());
                            List<TicketDecorator> decorators = TicketDecorator
                                    .decorate(e.getValue(),
                                            !hasPaidSupplement && configurationManager.getBooleanConfigValue(
                                                    Configuration.from(event.getOrganizationId(), event.getId(),
                                                            category.getId(), ALLOW_FREE_TICKETS_CANCELLATION),
                                                    false),
                                            eventManager.checkTicketCancellationPrerequisites(),
                                            ticket -> ticketHelper.findTicketFieldConfigurationAndValue(
                                                    event.getId(), ticket, locale),
                                            true, (t) -> "tickets['" + t.getUuid() + "'].");
                            return Pair.of(category, decorators);
                        }).collect(toList()));
                return "/event/reservation-page";
            }).orElseGet(() -> redirectReservation(Optional.empty(), eventName, reservationId)))
            .orElse("redirect:/");
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl.DocumentChartDataManagerImpl.java

@Override
public void createPersonDocumentHistoryChart(final AbstractOrderedLayout content, final String personId) {

    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);

    final DataSeries dataSeries = new DataSeries();

    final Series series = new Series();

    final Map<String, List<ViewRiksdagenPoliticianDocumentDailySummary>> allMap = getViewRiksdagenPoliticianDocumentDailySummaryMap();

    final List<ViewRiksdagenPoliticianDocumentDailySummary> itemList = allMap
            .get(personId.toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING).trim());

    if (itemList != null) {

        final Map<String, List<ViewRiksdagenPoliticianDocumentDailySummary>> map = itemList.parallelStream()
                .filter(t -> t != null).collect(Collectors.groupingBy(
                        t -> StringUtils.defaultIfBlank(t.getEmbeddedId().getDocumentType(), NO_INFO)));

        addDocumentHistoryByPersonData(simpleDateFormat, dataSeries, series, map);
    }//from  ww  w.j  a  v  a2s. c  om

    addChart(content, "Document history ", new DCharts().setDataSeries(dataSeries)
            .setOptions(chartOptions.createOptionsXYDateFloatLegendOutside(series)).show());
}

From source file:com.uber.hoodie.common.model.HoodieTestUtils.java

public static void writeRecordsToLogFiles(FileSystem fs, String basePath, Schema schema,
        List<HoodieRecord> updatedRecords) {
    Map<HoodieRecordLocation, List<HoodieRecord>> groupedUpdated = updatedRecords.stream()
            .collect(Collectors.groupingBy(HoodieRecord::getCurrentLocation));

    groupedUpdated.entrySet().forEach(s -> {
        HoodieRecordLocation location = s.getKey();
        String partitionPath = s.getValue().get(0).getPartitionPath();

        Writer logWriter;/*w w  w. j  ava 2s. c om*/
        try {
            logWriter = HoodieLogFormat.newWriterBuilder().onParentPath(new Path(basePath, partitionPath))
                    .withFileExtension(HoodieLogFile.DELTA_EXTENSION).withFileId(location.getFileId())
                    .overBaseCommit(location.getCommitTime()).withFs(fs).build();

            Map<HoodieLogBlock.HeaderMetadataType, String> header = Maps.newHashMap();
            header.put(HoodieLogBlock.HeaderMetadataType.INSTANT_TIME, location.getCommitTime());
            header.put(HoodieLogBlock.HeaderMetadataType.SCHEMA, schema.toString());
            logWriter.appendBlock(new HoodieAvroDataBlock(s.getValue().stream().map(r -> {
                try {
                    GenericRecord val = (GenericRecord) r.getData().getInsertValue(schema).get();
                    HoodieAvroUtils.addHoodieKeyToRecord(val, r.getRecordKey(), r.getPartitionPath(), "");
                    return (IndexedRecord) val;
                } catch (IOException e) {
                    return null;
                }
            }).collect(Collectors.toList()), header));
            logWriter.close();
        } catch (Exception e) {
            fail(e.toString());
        }
    });
}

From source file:eu.ggnet.dwoss.misc.op.listings.SalesListingProducerOperation.java

/**
 * Generates XLS files for units in a specific sales channel.
 * The lists are seperated by brand./*from w  w  w  . j a v  a2 s .c  o m*/
 * <p>
 * @param channel the saleschannel
 * @return XLS files for units in a specific sales channel.
 */
private Map<TradeName, Collection<FileJacket>> generateXlsListings(SalesChannel channel) {
    SubMonitor m = monitorFactory.newSubMonitor("Listen fr " + channel.getName() + " erstellen", 100);
    m.start();
    List<StockUnit> stockUnits = new StockUnitEao(stockEm).findByNoLogicTransactionAndPresentStock();
    List<UniqueUnit> uniqueUnits = new UniqueUnitEao(uuEm).findByIds(toUniqueUnitIds(stockUnits));

    Map<TradeName, List<UniqueUnit>> units = uniqueUnits.stream()
            .collect(Collectors.groupingBy(uu -> uu.getProduct().getTradeName()));

    m.worked(2, "prfe und filtere Gerte");
    Map<TradeName, Collection<FileJacket>> files = new HashMap<>();

    for (TradeName k : units.keySet()) {
        List<UniqueUnit> uus = units.get(k);
        Collections.sort(uus, new UniqueUnitComparator());
        List<Object[]> rows = new ArrayList<>();
        for (UniqueUnit get : uus) {
            UniqueUnit uu = get;
            Product p = uu.getProduct();

            // Cases to filter out.
            if (uu.getSalesChannel() != channel)
                continue;
            if (!uu.hasPrice((channel == SalesChannel.CUSTOMER ? PriceType.CUSTOMER : PriceType.RETAILER)))
                continue;

            Object[] row = { uu.getRefurbishId(), p.getPartNo(), p.getGroup().getNote(),
                    p.getTradeName().getName(), p.getName(), p.getDescription(), uu.getWarranty().getName(),
                    uu.getWarrentyValid(), UniqueUnitFormater.toSingleLineAccessories(uu),
                    uu.getCondition().getNote(), UniqueUnitFormater.toSingleLineComment(uu),
                    uu.getPrice(PriceType.RETAILER), uu.getPrice(PriceType.CUSTOMER),
                    (!uu.hasPrice(PriceType.CUSTOMER) ? null
                            : MathUtil.roundedApply(uu.getPrice(PriceType.CUSTOMER), GlobalConfig.TAX, 0)), };
            rows.add(row);
        }
        if (rows.isEmpty())
            continue;

        m.worked(5, "creating File, Gerte: " + rows.size());

        STable unitTable = new STable();
        unitTable.setTableFormat(
                new CFormat(CENTER, TOP, new CBorder(Color.GRAY, CBorder.LineStyle.THIN), true));
        unitTable.setHeadlineFormat(
                new CFormat(CFormat.FontStyle.BOLD, Color.BLACK, Color.LIGHT_GRAY, CENTER, MIDDLE));
        unitTable.setRowHeight(1000);

        unitTable.add(new STableColumn("SopoNr", 12));
        unitTable.add(new STableColumn("ArtikelNr", 15));
        unitTable.add(new STableColumn("Warengruppe", 18));
        unitTable.add(new STableColumn("Hersteller", 15));
        unitTable.add(new STableColumn("Bezeichnung", 30));
        unitTable.add(new STableColumn("Beschreibung", 60, LFT));
        unitTable.add(new STableColumn("Garantie", 18, LFT));
        unitTable.add(new STableColumn("Garantie bis", 18, new CFormat(Representation.SHORT_DATE)));
        unitTable.add(new STableColumn("Zubehr", 30, LFT));
        unitTable.add(new STableColumn("optische Bewertung", 25));
        unitTable.add(new STableColumn("Bemerkung", 50, LFT));
        unitTable.add(new STableColumn("Hndler", 15, EURO));
        unitTable.add(new STableColumn("Endkunde", 15, EURO));
        unitTable.add(new STableColumn("E.inc.Mwst", 15, EURO));
        unitTable.setModel(new STableModelList(rows));

        CCalcDocument cdoc = new TempCalcDocument();
        cdoc.add(new CSheet("Sonderposten", unitTable));
        files.put(k, Arrays.asList(new FileJacket(k.getName() + " Liste", ".xls",
                LucidCalc.createWriter(LucidCalc.Backend.XLS).write(cdoc))));
    }
    m.finish();
    return files;
}