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:se.uu.it.cs.recsys.constraint.util.ConstraintResultConverter.java

public Map<Integer, Set<Course>> convertToMap(Domain[] solution) {
    Map<Integer, Set<Course>> result = new HashMap<>();

    if (solution == null || solution.length == 0) {
        LOGGER.debug("Input result is empty!");
        return result;
    }/*from www .j  av a2 s.co  m*/

    int i = 1;
    for (Domain var : solution) {
        LOGGER.debug("Solution domain to be converted: " + var.toString());

        SetDomainValueEnumeration ve = (SetDomainValueEnumeration) (var.valueEnumeration());

        Set<Integer> courseIds = new HashSet<>();

        while (ve.hasMoreElements()) {
            int[] elemArray = ve.nextSetElement().toIntArray();

            for (int elem : elemArray) {
                courseIds.add(elem);
            }
        }

        Set<se.uu.it.cs.recsys.persistence.entity.Course> courseEntities = this.courseRepository
                .findByAutoGenIds(courseIds);

        Set<Course> courseInfoSet = courseEntities.stream().map(course -> {
            Course courseInfo = new Course.Builder().setName(course.getName())
                    .setCredit(course.getCredit().getCredit()).setCode(course.getCode())
                    .setLevel(CourseLevel.ofDBString(course.getLevel().getLevel()))
                    .setTaughtYear(Integer.valueOf(course.getTaughtYear()))
                    .setStartPeriod(Integer.valueOf(course.getStartPeriod()))
                    .setEndPeriod(Integer.valueOf(course.getEndPeriod())).build();

            return courseInfo;
        }).collect(Collectors.toSet());

        result.put(i, courseInfoSet);

        i++;
    }

    return result;
}

From source file:io.ingenieux.lambada.maven.LambadaGenerateMojo.java

@Override
protected void executeInternal() throws Exception {
    outputFile.getParentFile().mkdirs();

    final Set<Method> methodsAnnotatedWith = extractRuntimeAnnotations(LambadaFunction.class);

    // TODO: Validate clashing paths

    final TreeSet<LambadaFunctionDefinition> definitionTreeSet = methodsAnnotatedWith.stream()
            .map(f -> Unthrow.wrap(this::extractFunctionDefinitions, f))
            .collect(Collectors.toCollection(TreeSet::new));

    final List<LambadaFunctionDefinition> defList = new ArrayList<>(definitionTreeSet);

    OBJECT_MAPPER.writeValue(new FileOutputStream(outputFile), defList);
}

From source file:com.thoughtworks.go.server.service.MagicalMaterialAndMaterialConfigConversionTest.java

@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*from   w w w  .  j  a  v a 2  s  . c  o m*/
    provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));
    Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com/thoughtworks");
    List<Class> reflectionsSubTypesOf = candidateComponents.stream()
            .map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {
                try {
                    return Class.forName(s);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());

    reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);

    List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();

    assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf,
            allExpectedMaterialConfigImplementations);
}

From source file:info.archinnov.achilles.internals.metamodel.SetProperty.java

@Override
public Set<VALUETO> encodeFromJavaInternal(Set<VALUEFROM> set) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("Encode from Java '%s' set %s to CQL type", fieldName, set));
    }// ww  w .j ava2 s  .com
    return new HashSet<>(set.stream().map(value -> valueProperty.encodeFromRaw(value)).collect(toSet()));
}

From source file:com.graphaware.module.es.search.Searcher.java

private <T extends PropertyContainer> List<SearchMatch<T>> buildSearchMatches(SearchResult searchResult) {
    List<SearchMatch<T>> matches = new ArrayList<>();
    Set<Map.Entry<String, JsonElement>> entrySet = searchResult.getJsonObject().entrySet();
    entrySet.stream().filter((item) -> (item.getKey().equalsIgnoreCase("hits")))
            .map((item) -> (JsonObject) item.getValue()).filter((hits) -> (hits != null))
            .map((hits) -> hits.getAsJsonArray("hits")).filter((hitsArray) -> (hitsArray != null))
            .forEach((hitsArray) -> {
                for (JsonElement element : hitsArray) {
                    JsonObject obj = (JsonObject) element;

                    // extract the result score
                    JsonElement _score = obj.get("_score");
                    Double score = null;
                    if (_score != null && !_score.isJsonNull() && _score.isJsonPrimitive()
                            && ((JsonPrimitive) _score).isNumber()) {
                        score = _score.getAsDouble();
                    }//from   w w  w. j  a v a 2s. co  m

                    // extract the result id
                    String keyValue = obj.get("_id") != null ? obj.get("_id").getAsString() : null;
                    if (keyValue == null) {
                        LOG.warn("No key found in search result: " + obj.getAsString());
                    } else {
                        matches.add(new SearchMatch<>(keyValue, score));
                    }
                }
            });
    return matches;
}

From source file:io.syndesis.dao.validation.UniquePropertyValidator.java

@Override
public boolean isValid(final WithId<?> value, final ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }//  w ww. ja  v a  2s . c o  m

    final PropertyAccessor bean = new BeanWrapperImpl(value);

    final String propertyValue = String.valueOf(bean.getPropertyValue(property));

    @SuppressWarnings({ "rawtypes", "unchecked" })
    final Class<WithId> modelClass = (Class) value.getKind().modelClass;

    @SuppressWarnings("unchecked")
    final Set<String> ids = dataManager.fetchIdsByPropertyValue(modelClass, property, propertyValue);

    final boolean isUnique = ids.isEmpty() || value.getId().map(id -> ids.contains(id)).orElse(false);

    if (!isUnique) {
        if (ids.stream().allMatch(id -> consideredValidByException(modelClass, id))) {
            return true;
        }

        context.disableDefaultConstraintViolation();
        context.unwrap(HibernateConstraintValidatorContext.class)
                .addExpressionVariable("nonUnique", propertyValue)
                .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(property).addConstraintViolation();
    }

    return isUnique;
}

From source file:com.netflix.conductor.core.events.EventProcessor.java

private void refresh() {
    Set<String> events = ms.getEventHandlers().stream().map(eh -> eh.getEvent()).collect(Collectors.toSet());
    List<ObservableQueue> created = new LinkedList<>();
    events.stream().forEach(event -> queuesMap.computeIfAbsent(event, s -> {
        ObservableQueue q = EventQueues.getQueue(event, false);
        created.add(q);/*w w  w.  j  a v  a 2 s  .  c  om*/
        return q;
    }));
    if (!created.isEmpty()) {
        created.stream().filter(q -> q != null).forEach(queue -> listen(queue));
    }
}

From source file:de.dentrassi.rpm.builder.YumMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    this.logger = new Logger(getLog());

    try {//from  ww w .j  av  a  2s.c  o m
        final Builder builder = new RepositoryCreator.Builder();
        builder.setTarget(new FileSystemSpoolOutTarget(this.outputDirectory.toPath()));

        if (!this.skipSigning) {
            final PGPPrivateKey privateKey = SigningHelper.loadKey(this.signature, this.logger);
            if (privateKey != null) {
                final int digestAlgorithm = HashAlgorithm.from(this.signature.getHashAlgorithm()).getValue();
                builder.setSigning(output -> new SigningStream(output, privateKey, digestAlgorithm, false,
                        "RPM builder Mojo - de.dentrassi.maven:rpm"));
            }
        }

        final RepositoryCreator creator = builder.build();

        this.packagesPath = new File(this.outputDirectory, "packages");
        Files.createDirectories(this.packagesPath.toPath());

        final Collection<Path> paths = Lists.newArrayList();

        if (!this.skipDependencies) {
            final Set<Artifact> deps = this.project.getArtifacts();
            if (deps != null) {
                paths.addAll(deps.stream()//
                        .filter(d -> d.getType().equalsIgnoreCase("rpm"))//
                        .map(d -> d.getFile().toPath())//
                        .collect(Collectors.toList()));
            }
        } else {
            this.logger.debug("Skipped RPM artifacts from maven dependencies");
        }

        if (this.files != null) {
            paths.addAll(this.files.stream().map(f -> f.toPath()).collect(Collectors.toList()));
        }
        if (this.directories != null) {
            for (final File dir : this.directories) {
                Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        if (file.getFileName().toString().toLowerCase().endsWith(".rpm")) {
                            paths.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        }

        addPackageList(creator, paths);
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to write repository", e);
    }
}

From source file:se.uu.it.cs.recsys.constraint.util.ConstraintResultConverter.java

public Map<Integer, Set<Course>> convert(SetVar[] in) {
    Map<Integer, Set<Course>> result = new HashMap<>();

    if (in == null || in.length == 0) {
        LOGGER.debug("Input result is empty!");
        return result;
    }/*ww w .j  a  v  a  2 s.c o  m*/

    int i = 1;
    for (SetVar var : in) {
        LOGGER.debug("SetVar to be converted: " + var.toString());

        if (var.dom() == null || var.dom().isEmpty()) {
            LOGGER.debug("The {}th var domain is empty.", i);
            i++;
            continue;
        }

        SetDomainValueEnumeration ve = (SetDomainValueEnumeration) (var.dom().valueEnumeration());

        Set<Integer> courseIds = new HashSet<>();

        while (ve.hasMoreElements()) {
            int[] elemArray = ve.nextSetElement().toIntArray();

            for (int elem : elemArray) {
                courseIds.add(elem);
            }
        }

        Set<se.uu.it.cs.recsys.persistence.entity.Course> courseEntities = this.courseRepository
                .findByAutoGenIds(courseIds);

        Set<Course> courseInfoSet = courseEntities.stream().map(course -> {
            Course courseInfo = new Course.Builder().setName(course.getName())
                    .setCredit(course.getCredit().getCredit()).setCode(course.getCode())
                    .setLevel(CourseLevel.ofDBString(course.getLevel().getLevel()))
                    .setTaughtYear(Integer.valueOf(course.getTaughtYear()))
                    .setStartPeriod(Integer.valueOf(course.getStartPeriod()))
                    .setEndPeriod(Integer.valueOf(course.getEndPeriod())).build();

            return courseInfo;
        }).collect(Collectors.toSet());

        result.put(i, courseInfoSet);

        i++;
    }

    return result;
}

From source file:software.uncharted.service.ImageService.java

public Set<Image> searchByHistogram(String histogram) {
    // Create a set of all the lsh clusters
    final Set<Image> lshUnions = Sets.newHashSet();
    imageHashers.stream().map(hasher -> hasher.calcLSHstring(histogram))
            .forEach(lsh -> lshUnions.addAll(searchByHash(lsh)));

    // filter to once that have close histograms
    return lshUnions.stream().filter(i -> i.hasSimilarHistogram(histogram)).collect(Collectors.toSet());
}