Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:de.ks.flatadocdb.metamodel.Parser.java

private Field resolveExactlyOneField(Class<?> clazz, Set<Field> allFields,
        Class<? extends Annotation> annotation, String member, boolean hasToExist) {
    Set<Field> idFields = allFields.stream().filter(f -> f.isAnnotationPresent(annotation))
            .collect(Collectors.toSet());
    check(idFields, c -> c.size() > 1,
            c -> "Multiple " + member + " fields found on " + clazz.getName() + ": " + c);
    if (hasToExist) {
        check(idFields, c -> c.size() == 0, c -> "No " + member + " field found on " + clazz.getName() + ".");
        return idFields.iterator().next();
    } else {/*from  w ww  . j a va2 s. c  o  m*/
        if (idFields.isEmpty()) {
            return null;
        } else {
            return idFields.iterator().next();
        }
    }
}

From source file:opendial.gui.stateviewer.DistributionViewer.java

private List<XYSeries> extractSeries(DensityFunction function) throws DialException {

    List<XYSeries> series = new ArrayList<XYSeries>();

    for (int i = 0; i < function.getDimensionality(); i++) {
        series.add(new XYSeries("dimension " + i));
    }//from   ww  w .j  a v a 2 s. co m

    Consumer<double[]> addToSeries = p -> {
        double density = function.getDensity(p);
        for (int d = 0; d < p.length; d++) {
            series.get(d).add(p[d], density);
        }
    };

    Set<double[]> points = function.discretise(500).keySet();
    points.stream().forEach(addToSeries);

    for (XYSeries serie : series) {
        boolean doSmoothing = (function instanceof KernelDensityFunction)
                || (function instanceof DirichletDensityFunction);
        while (doSmoothing) {
            int nbFluctuations = 0;
            double prevPrevY = serie.getY(0).doubleValue();
            double prevY = serie.getY(1).doubleValue();
            for (int i = 2; i < serie.getItemCount(); i++) {
                double currentY = serie.getY(i).doubleValue();
                if (Math.signum(prevY - prevPrevY) != Math.signum(currentY - prevY)) {
                    double avg = (prevPrevY + prevY + currentY) / 3.0;
                    serie.updateByIndex(i - 2, avg);
                    serie.updateByIndex(i - 1, avg);
                    serie.updateByIndex(i, avg);
                    nbFluctuations++;
                }
                prevPrevY = prevY;
                prevY = currentY;
            }
            doSmoothing = (nbFluctuations > points.size() / 2) ? true : false;
        }

    }
    return series;
}

From source file:opendial.gui.utils.DistributionViewer.java

private List<XYSeries> extractSeries(DensityFunction function) {

    List<XYSeries> series = new ArrayList<XYSeries>();

    for (int i = 0; i < function.getDimensions(); i++) {
        series.add(new XYSeries("dimension " + i));
    }//from w  w w .  java2s.  c o m

    Consumer<double[]> addToSeries = p -> {
        double density = function.getDensity(p);
        for (int d = 0; d < p.length; d++) {
            series.get(d).add(p[d], density);
        }
    };

    Set<double[]> points = function.discretise(500).keySet();
    points.stream().forEach(addToSeries);

    for (XYSeries serie : series) {
        boolean doSmoothing = (function instanceof KernelDensityFunction)
                || (function instanceof DirichletDensityFunction);
        while (doSmoothing) {
            int nbFluctuations = 0;
            double prevPrevY = serie.getY(0).doubleValue();
            double prevY = serie.getY(1).doubleValue();
            for (int i = 2; i < serie.getItemCount(); i++) {
                double currentY = serie.getY(i).doubleValue();
                if (Math.signum(prevY - prevPrevY) != Math.signum(currentY - prevY)) {
                    double avg = (prevPrevY + prevY + currentY) / 3.0;
                    serie.updateByIndex(i - 2, avg);
                    serie.updateByIndex(i - 1, avg);
                    serie.updateByIndex(i, avg);
                    nbFluctuations++;
                }
                prevPrevY = prevY;
                prevY = currentY;
            }
            doSmoothing = (nbFluctuations > points.size() / 2) ? true : false;
        }

    }
    return series;
}

From source file:com.wso2.code.quality.matrices.Reviewer.java

/**
 * for finding the reviewers of each commit and storing them in a Set
 *
 * @param commitHashObtainedForPRReview commit hash Set for finding the pull requests
 * @param githubToken                   github token for accessing github REST API
 *//*  w  w  w  . j  a  va 2  s . c om*/
public void findReviewers(Set<String> commitHashObtainedForPRReview, String githubToken,
        RestApiCaller restApiCaller) {

    commitHashObtainedForPRReview.stream().forEach(commitHashForFindingReviewers -> {
        setSearchPullReqeustAPI(commitHashForFindingReviewers);
        // calling the github search API
        JSONObject rootJsonObject = null;
        try {
            rootJsonObject = (JSONObject) restApiCaller.callApi(getSearchPullReqeustAPI(), githubToken, false,
                    true);
        } catch (CodeQualityMatricesException e) {
            logger.error(e.getMessage(), e.getCause());
            System.exit(1);
        }
        // reading thus saved json file
        if (rootJsonObject != null) {
            savePrNumberAndRepoName(rootJsonObject);
        }
    });

    logger.info(
            "PR numbers which introduce bug lines of code with their relevant repository are saved successfully to mapContainingPRNoAgainstRepoName map");
    saveReviewersToList(githubToken, restApiCaller);
    logger.info(
            "List of approved reviwers and comment users of the PRs which introduce bug lines to repository are saved in commentedReviewers and approvedReviewers list ");
    // printing the list of reviewers of pull requests
    printReviewUsers();
    logger.info("Names of approved reviewers and commented reviewers are printed successfully");
}

From source file:diffhunter.Indexer.java

private void Set_Parameters() {

    dic_synchrinzer_genes.clear();/*from ww  w  .jav a  2s  .c  om*/
    Set<String> keys_ = dic_genes.keySet();
    keys_.stream().forEach((inner_keyKeys_) -> {
        dic_synchrinzer_genes.put(inner_keyKeys_, Boolean.TRUE);
    });
}

From source file:gr.cti.android.experimentation.controller.api.SmartphoneController.java

private TreeSet<UsageEntry> extractUsageTimes(final Set<Result> results) {
    final Map<String, Long> res = new TreeMap<>();
    final SortedSet<Long> timestamps = results.stream().map(Result::getTimestamp)
            .collect(Collectors.toCollection(TreeSet::new));
    DateTime start = null;/*from ww  w .j av  a 2 s .  c  om*/
    DateTime lastDay = null;
    for (final Long timestamp : timestamps) {
        final DateTime curDateTime = new DateTime(timestamp);
        if (start == null) {
            start = new DateTime(timestamp);
        } else {
            if (start.withMillisOfDay(0).getMillis() == curDateTime.withMillisOfDay(0).getMillis()) {
                lastDay = new DateTime(timestamp);
            } else {
                if (lastDay != null) {
                    long diff = (lastDay.getMillis() - start.getMillis()) / 1000 / 60;
                    res.put(dfDay.format(lastDay.withMillisOfDay(0).getMillis()), diff);
                }
                start = null;
                lastDay = null;
            }
        }
    }

    return res.keySet().stream().map(dateKey -> new UsageEntry(dateKey, res.get(dateKey)))
            .collect(Collectors.toCollection(TreeSet::new));
}

From source file:org.fenixedu.academic.thesis.ui.service.StudentCandidaciesService.java

public Set<ThesisProposalsConfiguration> getSuggestedConfigs(Student student) {

    Set<ThesisProposalsConfiguration> suggestedConfigs = new HashSet<ThesisProposalsConfiguration>();
    student.getActiveRegistrations().forEach(reg -> {
        Set<ThesisProposalsConfiguration> regConfigs = getConfigurationsForRegistration(reg);

        Set<ThesisProposalsConfiguration> openRegConfigs = regConfigs.stream()
                .filter(config -> config.getCandidacyPeriod().containsNow()).collect(Collectors.toSet());

        if (openRegConfigs.isEmpty()) {
            Optional<ThesisProposalsConfiguration> nextConfig = regConfigs.stream()
                    .max(ThesisProposalsConfiguration.COMPARATOR_BY_PROPOSAL_PERIOD_START_ASC);
            if (nextConfig.isPresent()) {
                suggestedConfigs.add(nextConfig.get());
            }//w ww.  j a  v a 2 s .  c  o m
        } else {
            suggestedConfigs.addAll(openRegConfigs);
        }
    });

    return suggestedConfigs;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.stylesheet.StylesheetValidationTest.java

private Stream<Class<? extends S2SFormGenerator>> getGeneratorsToTest() {
    final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);//from  ww w  . j  av  a 2s . c  o m

    final TypeFilter testableFilter = (metadataReader,
            metadataReaderFactory) -> new AnnotationTypeFilter(FormGenerator.class).match(metadataReader,
                    metadataReaderFactory)
                    && new AssignableTypeFilter(S2SFormGenerator.class).match(metadataReader,
                            metadataReaderFactory)
                    && !metadataReader.getClassMetadata().isAbstract()
                    && !BROKEN_GENERATORS.contains(metadataReader.getClassMetadata().getClassName());

    provider.addIncludeFilter(testableFilter);
    provider.addExcludeFilter(new AssignableTypeFilter(DynamicNamespace.class));
    provider.setResourceLoader(new PathMatchingResourcePatternResolver(this.getClass().getClassLoader()));
    final Set<BeanDefinition> generators = provider
            .findCandidateComponents("org.kuali.coeus.s2sgen.impl.generate.support");
    return generators.stream().map(generator -> {
        try {
            @SuppressWarnings("unchecked")
            final Class<? extends S2SFormGenerator> clazz = (Class<? extends S2SFormGenerator>) Class
                    .forName(generator.getBeanClassName());
            return clazz;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:kuona.jenkins.analyser.JenkinsProcessor.java

public void collectMetrics(BuildMetrics metrics) {
    try {//from w ww  . java2 s  .  c o m
        Utils.puts("Updating " + getURI());
        final int[] jobCount = { 0 };
        final int[] buildCount = { 0 };
        Set<String> jobNames = getJobs().keySet();
        jobCount[0] = jobNames.size();
        jobNames.stream().forEach(key -> {
            try {
                JobWithDetails job = getJob(key);
                Utils.puts("Updating " + key);
                final List<Build> builds = job.details().getBuilds();

                buildCount[0] += builds.size();

                builds.stream().forEach(buildDetails -> {
                    try {
                        final BuildWithDetails details = buildDetails.details();
                        Timestamp timestamp = new Timestamp(details.getTimestamp());

                        Date buildDate = new Date(timestamp.getTime());

                        int year = buildDate.getYear() + 1900;

                        if (!metrics.activity.containsKey(year)) {
                            metrics.activity.put(year, new int[12]);
                        }

                        int[] yearMap = metrics.activity.get(year);
                        yearMap[buildDate.getMonth()] += 1;

                        if (details.getResult() == null) {
                            metrics.buildCountsByResult.put(BuildResult.UNKNOWN,
                                    metrics.buildCountsByResult.get(BuildResult.UNKNOWN) + 1);
                        } else {
                            metrics.buildCountsByResult.put(details.getResult(),
                                    metrics.buildCountsByResult.get(details.getResult()) + 1);
                        }

                        metrics.byDuration.collect(details.getDuration());
                        final List<Map> actions = details.getActions();
                        actions.stream().filter(action -> action != null).forEach(action -> {
                            if (action.containsKey("causes")) {
                                List<HashMap> causes = (List<HashMap>) action.get("causes");

                                causes.stream().filter(cause -> cause.containsKey("shortDescription"))
                                        .forEach(cause -> {
                                            metrics.triggers.add((String) cause.get("shortDescription"));
                                        });
                            }
                        });
                        metrics.completedBuilds.add(details);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        metrics.dashboardServers.add(new HashMap<String, Object>() {
            {
                MainView serverInfo = getServerInfo();
                put("name", serverInfo.getName());
                put("description", serverInfo.getDescription());
                put("uri", getURI().toString());
                put("jobs", jobCount[0]);
                put("builds", buildCount[0]);
            }
        });

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:io.gravitee.gateway.services.sync.SyncManager.java

public void refresh() {
    logger.debug("Refreshing gateway state...");

    try {//w ww .  j  ava  2  s  .c  o m
        Set<io.gravitee.repository.management.model.Api> apis = apiRepository.findAll();

        // Determine deployed APIs store into events payload
        Set<Api> deployedApis = getDeployedApis(apis);

        Map<String, Api> apisMap = deployedApis.stream().filter(api -> api != null && hasMatchingTags(api))
                .collect(Collectors.toMap(Api::getId, api -> api));

        // Determine APIs to undeploy
        Set<String> apiToRemove = apiManager.apis().stream()
                .filter(api -> !apisMap.containsKey(api.getId()) || !hasMatchingTags(api)).map(Api::getId)
                .collect(Collectors.toSet());

        apiToRemove.forEach(apiManager::undeploy);

        // Determine APIs to update
        apisMap.keySet().stream().filter(apiId -> apiManager.get(apiId) != null).forEach(apiId -> {
            // Get local cached API
            Api deployedApi = apiManager.get(apiId);

            // Get API from store
            Api remoteApi = apisMap.get(apiId);

            if (deployedApi.getDeployedAt().before(remoteApi.getDeployedAt())) {
                apiManager.update(remoteApi);
            }
        });

        // Determine APIs to deploy
        apisMap.keySet().stream().filter(api -> apiManager.get(api) == null).forEach(api -> {
            Api newApi = apisMap.get(api);
            apiManager.deploy(newApi);
        });
    } catch (TechnicalException te) {
        logger.error("Unable to sync instance", te);
    }
}