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:org.matsim.contrib.dvrp.util.chart.RouteCharts.java

private static Map<TaskStatus, CoordSource> createLinkSourceByStatus(Schedule schedule) {
    Stream<DriveTask> tasks = Schedules.driveTasks(schedule);

    // creating lists of DriveTasks
    Map<TaskStatus, List<DriveTask>> taskListByStatus = tasks
            .collect(Collectors.groupingBy(t -> t.getStatus()));

    // creating LinkSources
    Map<TaskStatus, CoordSource> linkSourceByStatus = new EnumMap<>(TaskStatus.class);
    for (TaskStatus ts : TaskStatus.values()) {
        linkSourceByStatus.put(ts, ScheduleCoordSources.createCoordSource(taskListByStatus.get(ts)));
    }//from w w w  .j  av  a2  s . c  om

    return linkSourceByStatus;
}

From source file:com.github.lynxdb.server.core.repository.TimeSerieRepo.java

private ChainableIterator<ChainableIterator<TS>> findRows(UUID _vhost, String _name, Map<String, String> _tags,
        long _start, long _end) {
    /**/* ww  w  . ja v a  2s. c  om*/
     * @todo: I would like to find a way to avoid intense memory consumption
     * of this code. ie: avoiding the map<key,list<ts>> which stores all
     * rows to be queried... need to think about that later
     */
    return new ChainableIterator<ChainableIterator<TS>>() {

        Iterator<Map.Entry<Integer, List<TS>>> source = null;

        public void start() {
            long start = System.currentTimeMillis();
            source = ct
                    .query(QueryBuilder.select("group", "tags").from("list")
                            .where(QueryBuilder.eq("vhostid", _vhost)).and(QueryBuilder.eq("name", _name))
                            .and(QueryBuilder.gte("group", EntryRepo.getGroup(_start)))
                            .and(QueryBuilder.lte("group", EntryRepo.getGroup(_end)))
                            .orderBy(QueryBuilder.desc("group")))
                    .all().stream()
                    .map((Row t) -> new TS(t.getInt("group"), TagsSerializer.deserialize(t.getString("tags")),
                            t.getString("tags")))
                    .filter((TS t) -> _tags == null || _tags.entrySet().stream().allMatch(
                            (Map.Entry<String, String> tt) -> tt.getValue().equals(t.tags.get(tt.getKey()))))
                    .collect(Collectors.groupingBy((TS t) -> t.tags.hashCode())).entrySet().iterator();
            csMonit.queryScanCount.incrementAndGet();
            csMonit.tsScanQueryTime.add((int) (System.currentTimeMillis() - start));
        }

        @Override
        public boolean hasNext() {
            if (source == null) {
                start();
            }
            return source.hasNext();
        }

        @Override
        public ChainableIterator<TS> next() {
            if (source == null) {
                start();
            }
            return ChainableIterator.from(source.next().getValue().iterator());
        }
    };
}

From source file:com.qcadoo.mes.assignmentToShift.print.xls.AssignmentToShiftXlsHelper.java

private List<Entity> findCurrentAssignmentsToShift(final Date date, List<Entity> assignmentsToShift) {

    List<Entity> currentAssignments = Lists.newArrayList();

    Map<Entity, List<Entity>> assignmentsForCrews = assignmentsToShift.stream()
            .filter(assignment -> assignment.getBelongsToField(AssignmentToShiftFields.CREW) != null)
            .collect(Collectors
                    .groupingBy(assignment -> assignment.getBelongsToField(AssignmentToShiftFields.CREW)));
    assignmentsForCrews.put(null,//from  w  w w  .  ja  v  a 2 s .  c om
            assignmentsToShift.stream()
                    .filter(assignment -> assignment.getBelongsToField(AssignmentToShiftFields.CREW) == null)
                    .collect(Collectors.toList()));
    List<Entity> crews = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_CREW)
            .find().list().getEntities();
    for (Entity crew : crews) {
        currentAssignments.addAll(findCurrentAssignmentsToShiftForCrew(date, assignmentsForCrews.get(crew)));
    }
    currentAssignments.addAll(findCurrentAssignmentsToShiftForCrew(date, assignmentsForCrews.get(null)));
    return currentAssignments;
}

From source file:com.khartec.waltz.service.application.ApplicationService.java

public Map<AssetCodeRelationshipKind, List<Application>> findRelated(long appId) {

    List<Application> related = applicationDao.findRelatedByApplicationId(appId);

    Optional<Application> foundApp = related.stream().filter(app -> app.id().equals(Optional.of(appId)))
            .findFirst();/*from  ww  w  .j a v a2  s .co  m*/

    if (foundApp.isPresent()) {
        Application app = foundApp.get();

        Function<Application, AssetCodeRelationshipKind> classifier = relatedApp -> {

            boolean sameParent = relatedApp.parentAssetCode().equals(app.parentAssetCode());
            boolean sameCode = relatedApp.assetCode().equals(app.assetCode());
            boolean isParent = relatedApp.assetCode().equals(app.parentAssetCode());
            boolean isChild = relatedApp.parentAssetCode().equals(app.assetCode());

            if (sameCode) {
                return AssetCodeRelationshipKind.SHARING;
            } else if (isParent) {
                return AssetCodeRelationshipKind.PARENT;
            } else if (isChild) {
                return AssetCodeRelationshipKind.CHILD;
            } else if (sameParent && app.parentAssetCode().isPresent()) {
                return AssetCodeRelationshipKind.SIBLING;
            } else {
                return AssetCodeRelationshipKind.NONE;
            }
        };

        Map<AssetCodeRelationshipKind, List<Application>> grouped = related.stream()
                .filter(relatedApp -> relatedApp != app) // can do simple ref check here
                .collect(Collectors.groupingBy(classifier));

        return grouped;
    } else {
        return emptyMap();
    }

}

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

/**
 * Gets the view riksdagen party document daily summary map.
 *
 * @return the view riksdagen party document daily summary map
 */// w  w w .j a  va 2 s.c o  m
private Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> getViewRiksdagenPartyDocumentDailySummaryMap() {
    final DataContainer<ViewRiksdagenPartyDocumentDailySummary, RiksdagenDocumentPartySummaryEmbeddedId> politicianBallotSummaryDailyDataContainer = applicationManager
            .getDataContainer(ViewRiksdagenPartyDocumentDailySummary.class);

    return politicianBallotSummaryDailyDataContainer.getAll().parallelStream().filter(t -> t != null)
            .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPartyShortCode()
                    .toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING).trim()));
}

From source file:alfio.controller.api.admin.ExtensionApiController.java

@RequestMapping(value = "/setting/organization/{orgShortName}", method = RequestMethod.GET)
public Map<Integer, List<ExtensionParameterMetadataAndValue>> getParametersFor(
        @PathVariable("orgShortName") String orgShortName, Principal principal) {
    Organization org = organizationRepository.findByName(orgShortName).orElseThrow(IllegalStateException::new);
    ensureOrganization(principal, org);/* www  . j  ava2s.  co  m*/
    return extensionService
            .getConfigurationParametersFor("-" + org.getId(), "-" + org.getId() + "-%", "ORGANIZATION").stream()
            .collect(Collectors.groupingBy(ExtensionParameterMetadataAndValue::getExtensionId));
}

From source file:de.whs.poodle.controllers.instructor.FeedbackOverviewController.java

private List<FeedbackOverviewRowData> createRows(List<Statistic> courseTermStatistics) {
    // map from the studentId to all of the student's statistics
    Map<Student, List<Statistic>> studentToStatisticsMap = courseTermStatistics.stream()
            .collect(Collectors.groupingBy(Statistic::getStudent));

    // create the rows from the studentToStatisticsMap
    List<FeedbackOverviewRowData> rows = new ArrayList<>();

    for (Map.Entry<Student, List<Statistic>> e : studentToStatisticsMap.entrySet()) {
        Student student = e.getKey();//from  ww  w  .j  a  v a 2 s . c om
        List<Statistic> studentStatistics = e.getValue();

        /* studentStatistics is now the list of all statistics that the student
         * has created in this courseTerm. We now transform this list into a
         * map which maps each exercise to its statistic (a student can only
         * ever create one statistic for each exercise). */
        Map<Integer, Statistic> rootIdToStatisticMap = studentStatistics.stream()
                .collect(Collectors.toMap(Statistic::getExerciseRootId, Function.identity()));

        // create the row
        rows.add(new FeedbackOverviewRowData(student, rootIdToStatisticMap));
    }

    return rows;
}

From source file:com.dickthedeployer.dick.web.service.JobBuildService.java

private Build.Status determineBuildStatus(Build build) {
    Map<JobBuild.Status, List<JobBuild.Status>> statuses = jobBuildDao.findByBuild(build).stream()
            .map(JobBuild::getStatus).collect(Collectors.groupingBy(Function.identity()));
    if (!statuses.containsKey(JobBuild.Status.IN_PROGRESS) && !statuses.containsKey(JobBuild.Status.READY)) {
        if (statuses.containsKey(JobBuild.Status.FAILED)) {
            return Build.Status.FAILED;
        } else if (statuses.containsKey(JobBuild.Status.STOPPED)) {
            return Build.Status.STOPPED;
        } else {// w  w w  .j  a v  a2 s .  c  o  m
            return Build.Status.DEPLOYED_STAGE;
        }
    } else if (statuses.containsKey(JobBuild.Status.IN_PROGRESS)) {
        return Build.Status.IN_PROGRESS;
    } else {
        return Build.Status.READY;
    }
}

From source file:com.ggvaidya.scinames.summary.HigherStabilityView.java

private void generateHigherTaxonomyList(String higherTaxonomyColName) {
    Project project = projectView.getProject();
    DatasetColumn GENUS = DatasetColumn.fakeColumnFor("genus");
    DatasetColumn column;/*from  ww  w. j  a va 2  s. c o m*/

    if (higherTaxonomyColName.equals(""))
        column = GENUS;
    else if (datasetColumns.contains(DatasetColumn.of(higherTaxonomyColName))) {
        column = DatasetColumn.of(higherTaxonomyColName);
    } else {
        // Don't actually change until we have a valid column name.
        return;
    }

    // Group names by dataset column.
    Table<String, Dataset, Set<Name>> namesByDataset = HashBasedTable.create();

    for (String dsName : datasetNamesInOrder) {
        Dataset ds = datasetNames.get(dsName);

        if (column == GENUS) {
            Map<String, List<Name>> rowsByGenus = ds.getNamesInAllRows().stream()
                    .collect(Collectors.groupingBy(n -> n.getGenus()));

            for (String genus : rowsByGenus.keySet()) {
                namesByDataset.put(genus, ds, new HashSet<>(rowsByGenus.get(genus)));
            }
        } else {
            Map<DatasetRow, Set<Name>> namesByRow = ds.getNamesByRow();

            for (DatasetRow row : namesByRow.keySet()) {
                String colValue = row.get(column);
                if (colValue == null)
                    colValue = "(null)";

                if (!namesByDataset.contains(colValue, ds))
                    namesByDataset.put(colValue, ds, new HashSet<>());

                namesByDataset.get(colValue, ds).addAll(namesByRow.getOrDefault(row, new HashSet<>()));
            }
        }
    }

    // LOGGER.info("namesByDataset = " + namesByDataset);

    // By this point, namesByDataset should be ready to go.
    // So let's fill out precalc.
    precalc.clear();

    for (String rowName : namesByDataset.rowKeySet()) {
        precalc.put(rowName, "HigherTaxon", rowName);

        Set<Name> prevNames = new HashSet<>();

        for (String dsName : datasetNamesInOrder) {
            Dataset ds = datasetNames.get(dsName);
            Set<Name> names = namesByDataset.get(rowName, ds);

            // Missing?! Oh noes.
            if (names == null)
                names = new HashSet<>();

            // For now, let's just note down how many names we have.
            precalc.put(rowName, dsName + "_with_synonymy", calculateDifferenceWithSynonymy(prevNames, names));
            precalc.put(rowName, dsName + "_without_synonymy",
                    calculateDifferenceWithoutSynonymy(prevNames, names));

            // Set up prevNames for next time 'round
            prevNames = names;
        }
    }

    // LOGGER.info("precalc = " + precalc);

    // Tell everybody what we did.
    higherTaxaList.clear();
    higherTaxaList.addAll(namesByDataset.rowKeySet());
    LOGGER.info("higherTaxaList = " + higherTaxaList);

    controller.getTableView().refresh();
}

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

/**
 * Gets the view riksdagen politician document daily summary map.
 *
 * @return the view riksdagen politician document daily summary map
 *///from  w ww.  j  a  va  2s .  c  om
private Map<String, List<ViewRiksdagenPoliticianDocumentDailySummary>> getViewRiksdagenPoliticianDocumentDailySummaryMap() {
    final DataContainer<ViewRiksdagenPoliticianDocumentDailySummary, RiksdagenDocumentPersonSummaryEmbeddedId> politicianBallotSummaryDailyDataContainer = applicationManager
            .getDataContainer(ViewRiksdagenPoliticianDocumentDailySummary.class);

    return politicianBallotSummaryDailyDataContainer.getAll().parallelStream().filter(t -> t != null)
            .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPersonId()));
}