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.oneops.cms.cm.service.CmsCmProcessor.java

/**
 * Gets the from ci relations by multiple names
 *
 * @param fromId the from id/*from  ww w  . jav  a2s  .  c  om*/
 * @param relationNames the relation names
 * @param shortRelNames the short relation names
 * @return the from ci relations
 */
public Map<String, List<CmsCIRelation>> getFromCIRelationsByMultiRelationNames(long fromId,
        List<String> relationNames, List<String> shortRelNames) {
    List<CmsCIRelation> relations = getFromCIRelationsLocal(fromId, relationNames, shortRelNames);
    Map<String, List<CmsCIRelation>> relationsMap;
    if (relations != null) {
        relationsMap = relations.stream().collect(Collectors.groupingBy(CmsCIRelation::getRelationName));
    } else {
        relationsMap = Collections.emptyMap();
    }
    return relationsMap;
}

From source file:com.thinkbiganalytics.feedmgr.nifi.cache.NifiFlowCacheImpl.java

private Map<String, List<NifiFlowProcessor>> toFlowIdProcessorMap(Collection<NifiFlowProcessor> processors) {
    if (processors != null && !processors.isEmpty()) {
        return processors.stream().filter(nifiFlowProcessor -> nifiFlowProcessor.getFlowId() != null)
                .collect(Collectors.groupingBy(NifiFlowProcessor::getFlowId));
    }//from   ww w  . java  2s.c  o m
    return Collections.emptyMap();
}

From source file:com.thinkbiganalytics.feedmgr.nifi.cache.NifiFlowCacheImpl.java

private Map<String, List<NifiFlowProcessor>> toProcessorIdProcessorMap(
        Collection<NifiFlowProcessor> processors) {
    if (processors != null && !processors.isEmpty()) {
        return processors.stream().collect(Collectors.groupingBy(NifiFlowProcessor::getId));
    }//from   w  ww .  ja  v  a2 s .c o m
    return new HashMap<>();
}

From source file:com.ggvaidya.scinames.dataset.BinomialChangesSceneController.java

private AdditionalData<String, Map.Entry<String, String>> createSummaryAdditionalData() {
    List<Map.Entry<String, String>> summary = new ArrayList<>();

    // Calculate some summary values.
    long numChanges = potentialChanges.size();
    summary.add(new AbstractMap.SimpleEntry<String, String>("Number of binomial changes",
            String.valueOf(potentialChanges.size())));

    // How many have a note?
    summary.add(new AbstractMap.SimpleEntry<String, String>("Number of changes with annotations",
            String.valueOf(potentialChanges.stream().filter(ch -> ch.getNote().isPresent()).count())));

    // Calculate overall addition and deletion.

    // Summarize by types of change.
    Map<ChangeType, List<Change>> potentialChangesByType = potentialChanges.stream()
            .collect(Collectors.groupingBy(ch -> ch.getType()));
    summary.addAll(potentialChangesByType.keySet().stream().sorted()
            .map(type -> new AbstractMap.SimpleEntry<String, String>(
                    "Number of binomial changes of type '" + type + "'",
                    String.valueOf(potentialChangesByType.get(type).size())))
            .collect(Collectors.toList()));

    // Summarize by reason.
    Map<String, Long> potentialChangesByReason = potentialChanges.stream()
            .map(pc -> pc.getType() + " because of " + calculateReason(pc))
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    summary.addAll(potentialChangesByReason.keySet().stream().sorted()
            .map(reason -> new AbstractMap.SimpleEntry<String, String>(
                    "Number of binomial changes for reason '" + reason + "'",
                    potentialChangesByReason.get(reason).toString()))
            .collect(Collectors.toList()));

    // Make an additional data about it.
    Map<String, List<Map.Entry<String, String>>> map = new HashMap<>();
    map.put("Summary", summary);

    List<TableColumn<Map.Entry<String, String>, String>> cols = new ArrayList<>();

    TableColumn<Map.Entry<String, String>, String> colKey = new TableColumn<>("Property");
    colKey.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getKey()));
    cols.add(colKey);// www. j  a v  a2  s .  c om

    TableColumn<Map.Entry<String, String>, String> colValue = new TableColumn<>("Value");
    colValue.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
    cols.add(colValue);

    TableColumn<Map.Entry<String, String>, String> colPercent = new TableColumn<>("Percentage");
    colPercent.setCellValueFactory(cdf -> {
        String result = "NA";

        if (cdf.getValue() != null && cdf.getValue().getValue() != null
                && !cdf.getValue().getValue().equals("null")) {
            long longVal = Long.parseLong(cdf.getValue().getValue());

            result = (longVal == 0) ? "NA" : (((double) longVal / numChanges * 100) + "%");
        }

        return new ReadOnlyStringWrapper(result);
    });
    cols.add(colPercent);

    return new AdditionalData<String, Entry<String, String>>("Summary", Arrays.asList("Summary"), map, cols);
}

From source file:com.gs.collections.impl.parallel.SerialParallelLazyPerformanceTest.java

private double basicParallelLazyJava8GroupByPerformance(Set<String> iterable, String parameterType,
        java.util.function.Function<String, Alphagram> function, int count) {
    return TimeKeeper.logAverageMillisecondsToRun(
            "Parallel Java8 GroupBy using: " + parameterType + ' ' + this.getSimpleName(iterable) + " size: "
                    + this.formatSizeOf(iterable) + " cores: ?",
            () -> Verify.assertNotEmpty(iterable.parallelStream().collect(Collectors.groupingBy(function))),
            count, WARM_UP_COUNT);/*www.j a va2  s. c o  m*/
}

From source file:alfio.manager.TicketReservationManager.java

@Transactional
void cleanupExpiredReservations(Date expirationDate) {
    List<String> expiredReservationIds = ticketReservationRepository.findExpiredReservation(expirationDate);
    if (expiredReservationIds.isEmpty()) {
        return;/*from w ww .  ja v  a  2 s . c  o  m*/
    }

    specialPriceRepository.resetToFreeAndCleanupForReservation(expiredReservationIds);
    ticketRepository.resetCategoryIdForUnboundedCategories(expiredReservationIds);
    ticketFieldRepository.deleteAllValuesForReservations(expiredReservationIds);
    ticketRepository.freeFromReservation(expiredReservationIds);
    waitingQueueManager.cleanExpiredReservations(expiredReservationIds);

    //
    Map<Integer, List<ReservationIdAndEventId>> reservationIdsByEvent = ticketReservationRepository
            .getReservationIdAndEventId(expiredReservationIds).stream()
            .collect(Collectors.groupingBy(ReservationIdAndEventId::getEventId));
    reservationIdsByEvent.forEach((eventId, reservations) -> {
        Event event = eventRepository.findById(eventId);
        extensionManager.handleReservationsExpiredForEvent(event,
                reservations.stream().map(ReservationIdAndEventId::getId).collect(Collectors.toList()));
    });
    //
    ticketReservationRepository.remove(expiredReservationIds);
}

From source file:alfio.manager.TicketReservationManager.java

/**
 * Finds all the reservations that are "stuck" in payment status.
 * This could happen when there is an internal error after a successful credit card charge.
 *
 * @param expirationDate expiration date
 *///w  ww . j  ava2 s  .c  o m
public void markExpiredInPaymentReservationAsStuck(Date expirationDate) {
    List<String> stuckReservations = ticketReservationRepository.findStuckReservations(expirationDate);
    if (!stuckReservations.isEmpty()) {
        ticketReservationRepository.updateReservationsStatus(stuckReservations,
                TicketReservationStatus.STUCK.name());

        Map<Integer, List<ReservationIdAndEventId>> reservationsGroupedByEvent = ticketReservationRepository
                .getReservationIdAndEventId(stuckReservations).stream()
                .collect(Collectors.groupingBy(ReservationIdAndEventId::getEventId));

        reservationsGroupedByEvent.forEach((eventId, reservationIds) -> {
            Event event = eventRepository.findById(eventId);
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            notificationManager.sendSimpleEmail(event, organization.getEmail(), STUCK_TICKETS_SUBJECT,
                    () -> String.format(STUCK_TICKETS_MSG, event.getShortName()));

            extensionManager.handleStuckReservations(event,
                    reservationIds.stream().map(ReservationIdAndEventId::getId).collect(toList()));
        });
    }
}

From source file:alfio.manager.TicketReservationManager.java

List<SummaryRow> extractSummary(String reservationId, PriceContainer.VatStatus reservationVatStatus,
        Event event, Locale locale, PromoCodeDiscount promoCodeDiscount, TotalPrice reservationCost) {
    List<SummaryRow> summary = new ArrayList<>();
    List<TicketPriceContainer> tickets = ticketRepository.findTicketsInReservation(reservationId).stream()
            .map(t -> TicketPriceContainer.from(t, reservationVatStatus, event, promoCodeDiscount))
            .collect(toList());//w w  w . ja v a  2s  . c  om
    tickets.stream().collect(Collectors.groupingBy(TicketPriceContainer::getCategoryId))
            .forEach((categoryId, ticketsByCategory) -> {
                final int subTotal = ticketsByCategory.stream()
                        .mapToInt(TicketPriceContainer::getSummarySrcPriceCts).sum();
                final int subTotalBeforeVat = ticketsByCategory.stream()
                        .mapToInt(TicketPriceContainer::getSummaryPriceBeforeVatCts).sum();
                TicketPriceContainer firstTicket = ticketsByCategory.get(0);
                final int ticketPriceCts = firstTicket.getSummarySrcPriceCts();
                final int priceBeforeVat = firstTicket.getSummaryPriceBeforeVatCts();
                String categoryName = ticketCategoryRepository.getByIdAndActive(categoryId, event.getId())
                        .getName();
                summary.add(new SummaryRow(categoryName, formatCents(ticketPriceCts),
                        formatCents(priceBeforeVat), ticketsByCategory.size(), formatCents(subTotal),
                        formatCents(subTotalBeforeVat), subTotal, SummaryRow.SummaryType.TICKET));
            });

    summary.addAll(collectAdditionalServiceItems(reservationId, event).map(entry -> {
        String language = locale.getLanguage();
        AdditionalServiceText title = additionalServiceTextRepository.findBestMatchByLocaleAndType(
                entry.getKey().getId(), language, AdditionalServiceText.TextType.TITLE);
        if (!title.getLocale().equals(language) || title.getId() == -1) {
            log.debug("additional service {}: title not found for locale {}", title.getAdditionalServiceId(),
                    language);
        }
        List<AdditionalServiceItemPriceContainer> prices = generateASIPriceContainers(event, null).apply(entry)
                .collect(toList());
        AdditionalServiceItemPriceContainer first = prices.get(0);
        final int subtotal = prices.stream().mapToInt(AdditionalServiceItemPriceContainer::getSrcPriceCts)
                .sum();
        return new SummaryRow(title.getValue(), formatCents(first.getSrcPriceCts()),
                formatCents(first.getSrcPriceCts()), prices.size(), formatCents(subtotal),
                formatCents(subtotal), subtotal, SummaryRow.SummaryType.ADDITIONAL_SERVICE);
    }).collect(Collectors.toList()));

    Optional.ofNullable(promoCodeDiscount).ifPresent(promo -> {
        String formattedSingleAmount = "-"
                + (promo.getDiscountType() == DiscountType.FIXED_AMOUNT ? formatCents(promo.getDiscountAmount())
                        : (promo.getDiscountAmount() + "%"));
        summary.add(
                new SummaryRow(formatPromoCode(promo, ticketRepository.findTicketsInReservation(reservationId)),
                        formattedSingleAmount, formattedSingleAmount, reservationCost.getDiscountAppliedCount(),
                        formatCents(reservationCost.getDiscount()), formatCents(reservationCost.getDiscount()),
                        reservationCost.getDiscount(), SummaryRow.SummaryType.PROMOTION_CODE));
    });
    return summary;
}

From source file:alfio.manager.TicketReservationManager.java

private Stream<Pair<AdditionalService, List<AdditionalServiceItem>>> collectAdditionalServiceItems(
        String reservationId, Event event) {
    return additionalServiceItemRepository.findByReservationUuid(reservationId).stream()
            .collect(Collectors.groupingBy(AdditionalServiceItem::getAdditionalServiceId)).entrySet().stream()
            .map(entry -> Pair.of(additionalServiceRepository.getById(entry.getKey(), event.getId()),
                    entry.getValue()));//from w w  w .j  a va  2s. co  m
}