Java Code Examples for java.util.Set#stream()

The following examples show how to use java.util.Set#stream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EnhanceInteractions.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the alternative words from the dictionary.
 *
 * @param word the word
 * @return the alternative words (non null and always contains the word itself)
 */
private Stream<String> getAlternativeWords(Word word) {
  IndexWord indexWord = null;
  try {
    indexWord = dictionary.lookupIndexWord(word.getPos(), word.getLemma());
  } catch (final Exception e) {
    getMonitor().debug("Unable to find word in wordnet, defaulting to lemma form", e);
  }

  if (indexWord == null) {
    return Stream.of(word.getLemma());
  }

  Set<String> set = new HashSet<>();
  set.add(word.getLemma());
  for (Synset synset : indexWord.getSenses()) {
    for (net.sf.extjwnl.data.Word w : synset.getWords()) {
      set.add(w.getLemma());
    }
  }

  return set.stream();
}
 
Example 2
Source File: OpticalPathProvisionerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<Path> getKShortestPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher) {
    if (!(src instanceof DeviceId && dst instanceof DeviceId)) {
        return Stream.empty();
    }

    edges.add(Pair.of(src, dst));

    Set<Path> paths = new HashSet<>();
    List<Link> links = Stream.of(LINK1, LINK2, LINK3, LINK4, LINK5, LINK6)
            .collect(Collectors.toList());
    paths.add(new DefaultPath(PROVIDER_ID, links, new ScalarWeight(0)));

    // returns paths containing single path
    return paths.stream();
}
 
Example 3
Source File: CachedChronoVertex.java    From epcis with Apache License 2.0 6 votes vote down vote up
public Stream<CachedChronoVertex> getChronoVertexStream(final Direction direction, final BsonArray labels,
		final int branchFactor, final boolean setParallel) {

	HashSet<Long> labelIdxSet = null;
	if (labels != null) {
		labelIdxSet = convertToLabelIdxSet(labels);
	}

	if (direction.equals(Direction.OUT)) {
		return this.getOutChronoVertexStream(labelIdxSet, branchFactor, setParallel);
	} else if (direction.equals(Direction.IN))
		return this.getInChronoVertexStream(labelIdxSet, branchFactor, setParallel);
	else {
		Set<CachedChronoVertex> ret = this.getOutChronoVertexSet(labelIdxSet, branchFactor);
		ret.addAll(this.getInChronoVertexSet(labelIdxSet, branchFactor));
		if (setParallel)
			return ret.parallelStream();
		else
			return ret.stream();
	}
}
 
Example 4
Source File: TeachersWithGradesToSubmitGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Stream<User> getMembers() {
    Set<User> users = new HashSet<>();
    for (ExecutionCourse executionCourse : period.getExecutionCoursesWithDegreeGradesToSubmit(degreeCurricularPlan)) {
        for (Professorship professorship : executionCourse.getProfessorshipsSet()) {
            if (professorship.getResponsibleFor()) {
                if (professorship.getPerson() != null) {
                    User user = professorship.getPerson().getUser();
                    if (user != null) {
                        users.add(user);
                    }
                }
            }
        }
    }
    return users.stream();
}
 
Example 5
Source File: CachedChronoVertex.java    From epcis with Apache License 2.0 6 votes vote down vote up
public Stream<CachedChronoEdge> getChronoEdgeStream(final Direction direction, final BsonArray labels,
		final int branchFactor, final boolean setParallel) {

	HashSet<Long> labelIdxSet = null;
	if (labels != null) {
		labelIdxSet = convertToLabelIdxSet(labels);
	}

	if (direction.equals(Direction.OUT)) {
		return this.getOutChronoEdgeStream(labelIdxSet, branchFactor, setParallel);
	} else if (direction.equals(Direction.IN))
		return this.getInChronoEdgeStream(labelIdxSet, branchFactor, setParallel);
	else {
		Set<CachedChronoEdge> ret = this.getOutChronoEdgeSet(labelIdxSet, branchFactor);
		ret.addAll(this.getInChronoEdgeSet(labelIdxSet, branchFactor));
		if (setParallel)
			return ret.parallelStream();
		else
			return ret.stream();
	}
}
 
Example 6
Source File: ResponsibleForExecutionCourseGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Stream<User> getMembers() {
    Set<User> users = new HashSet<>();
    for (final ExecutionYear executionYear : Bennu.getInstance().getExecutionYearsSet()) {
        if (executionYear.isCurrent()) {
            for (final ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) {
                for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
                    for (final Professorship professorship : executionCourse.getProfessorshipsSet()) {
                        if (professorship.getResponsibleFor().booleanValue()) {
                            User user = professorship.getPerson().getUser();
                            if (user != null) {
                                users.add(user);
                            }
                        }
                    }
                }
            }
            break;
        }
    }
    return users.stream();
}
 
Example 7
Source File: GenerativeOperationalIT.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates a tree of patterns where such that each child is a generalisation of its parent pattern.
 * @param basePattern starting specific pattern
 * @param ctx schema(type) context
 * @return map containing parent->{children} mappings
 */
private static HashMultimap<Pattern, Pattern> generatePatternTree(Pattern basePattern, TransactionContext ctx, List<Operator> ops, int maxOps){
    HashMultimap<Pattern, Pattern> patternTree = HashMultimap.create();
    Set<Pattern> output = Operators.removeSubstitution().apply(basePattern, ctx).collect(Collectors.toSet());

    int applications = 0;
    while (!(output.isEmpty() || applications > maxOps)){
        Stream<Pattern> pstream = output.stream();
        for(Operator op : ops){
            pstream = pstream.flatMap(parent -> op.apply(parent, ctx).peek(child -> patternTree.put(parent, child)));
        }
        output = pstream.collect(Collectors.toSet());
        applications++;
    }
    return patternTree;
}
 
Example 8
Source File: DescribedOption.java    From selenium with Apache License 2.0 6 votes vote down vote up
private static Stream<DescribedOption> getAllFields(HasRoles hasRoles) {
  Set<DescribedOption> fields = new HashSet<>();
  Class<?> clazz = hasRoles.getClass();
  while (clazz != null && !Object.class.equals(clazz)) {
    for (Field field : clazz.getDeclaredFields()) {
      field.setAccessible(true);
      Parameter param = field.getAnnotation(Parameter.class);
      ConfigValue configValue = field.getAnnotation(ConfigValue.class);

      if (param != null && configValue != null) {
        fields.add(new DescribedOption(field.getGenericType(), param, configValue));
      }
    }
    clazz = clazz.getSuperclass();
  }
  return fields.stream();
}
 
Example 9
Source File: StudentGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Stream<Registration> getCampusBasedRegistrations() {
    Set<Registration> registrations = new HashSet<>();
    for (final ExecutionDegree executionDegree : ExecutionYear.readCurrentExecutionYear().getExecutionDegreesSet()) {
        if (executionDegree.getCampus().equals(campus)) {
            final DegreeCurricularPlan degreeCurricularPlan = executionDegree.getDegreeCurricularPlan();
            for (final StudentCurricularPlan studentCurricularPlan : degreeCurricularPlan.getStudentCurricularPlansSet()) {
                final Registration registration = studentCurricularPlan.getRegistration();
                if (registration != null && registration.isActive()) {
                    registrations.add(registration);
                }
            }
        }
    }
    return registrations.stream();
}
 
Example 10
Source File: TeachersWithMarkSheetsToConfirmGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Stream<User> getMembers() {
    Set<User> users = new HashSet<>();
    for (MarkSheet markSheet : period.getMarkSheetsToConfirm(degreeCurricularPlan)) {
        if (markSheet.getResponsibleTeacher().getPerson() != null) {
            User user = markSheet.getResponsibleTeacher().getPerson().getUser();
            if (user != null) {
                users.add(user);
            }
        }
    }
    return users.stream();
}
 
Example 11
Source File: CPLSARecommenderExample.java    From RankSys with Mozilla Public License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String userPath = args[0];
    String itemPath = args[1];
    String featurePath = args[2];
    String trainDataPath = args[3];
    String testDataPath = args[4];
    String featureDataPath = args[5];

    FastUserIndex<Long> userIndex = SimpleFastUserIndex.load(UsersReader.read(userPath, lp));
    FastItemIndex<Long> itemIndex = SimpleFastItemIndex.load(ItemsReader.read(itemPath, lp));
    FastFeatureIndex<String> featureIndex = SimpleFastFeatureIndex.load(FeatsReader.read(featurePath, sp));
    FastPreferenceData<Long, Long> trainData = SimpleFastPreferenceData.load(SimpleRatingPreferencesReader.get().read(trainDataPath, lp, lp), userIndex, itemIndex);
    FastPreferenceData<Long, Long> testData = SimpleFastPreferenceData.load(SimpleRatingPreferencesReader.get().read(testDataPath, lp, lp), userIndex, itemIndex);
    FastFeatureData<Long, String, Double> featureData = SimpleFastFeatureData.load(SimpleFeaturesReader.get().read(featureDataPath, lp, sp), itemIndex, featureIndex);

    int numIter = 100;

    Factorization<Long, Long> factorization = new CPLSAFactorizer<Long, Long, String>(numIter, featureData).factorize(trainData);
    Recommender<Long, Long> recommender = new MFRecommender<>(userIndex, itemIndex, factorization);

    Set<Long> targetUsers = testData.getUsersWithPreferences().collect(Collectors.toSet());
    RecommendationFormat<Long, Long> format = new SimpleRecommendationFormat<>(lp, lp);
    Function<Long, IntPredicate> filter = FastFilters.notInTrain(trainData);
    int maxLength = 100;
    RecommenderRunner<Long, Long> runner = new FastFilterRecommenderRunner<>(userIndex, itemIndex, targetUsers.stream(), filter, maxLength);

    System.out.println("Running cPLSA recommender");
    try (RecommendationFormat.Writer<Long, Long> writer = format.getWriter("cplsa")) {
        runner.run(recommender, writer);
    }
}
 
Example 12
Source File: CamelSupport.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public static Stream<CamelServiceBuildItem> services(ApplicationArchivesBuildItem archives, PathFilter pathFilter) {
    final Set<CamelServiceBuildItem> answer = new HashSet<>();
    final Predicate<Path> filter = pathFilter.asPathPredicate();

    for (ApplicationArchive archive : archives.getAllApplicationArchives()) {
        for (Path root : archive.getRootDirs()) {
            final Path resourcePath = root.resolve(CAMEL_SERVICE_BASE_PATH);

            if (!Files.isDirectory(resourcePath)) {
                continue;
            }

            safeWalk(resourcePath).filter(Files::isRegularFile).forEach(file -> {
                // the root archive may point to a jar file or the absolute path of
                // a project's build output so we need to relativize to make the
                // FastFactoryFinder work as expected
                Path key = root.relativize(file);

                if (filter.test(key)) {
                    String clazz = readProperties(file).getProperty("class");
                    if (clazz != null) {
                        answer.add(new CamelServiceBuildItem(key, clazz));
                    }
                }
            });
        }
    }

    return answer.stream();
}
 
Example 13
Source File: SchemaConceptImpl.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Stream<T> sups() {
    Set<T> superSet = new HashSet<>();

    T superParent = getThis();

    while (superParent != null && !Schema.MetaSchema.THING.getLabel().equals(superParent.label())) {
        superSet.add(superParent);

        //noinspection unchecked
        superParent = (T) superParent.sup();
    }

    return superSet.stream();
}
 
Example 14
Source File: TransactionImpl.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public final Stream<SchemaConcept> sups(SchemaConcept schemaConcept) {
    Set<SchemaConcept> superSet = new HashSet<>();

    while (schemaConcept != null) {
        superSet.add(schemaConcept);
        schemaConcept = schemaConcept.sup();
    }

    return superSet.stream();
}
 
Example 15
Source File: StudentGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Stream<Registration> getRegistrations(Degree degree) {
    Set<Registration> registrations = new HashSet<>();
    for (DegreeCurricularPlan degreeCurricularPlan : degree.getActiveDegreeCurricularPlans()) {
        for (StudentCurricularPlan studentCurricularPlan : degreeCurricularPlan.getStudentCurricularPlansSet()) {
            if (studentCurricularPlan.isActive()) {
                registrations.add(studentCurricularPlan.getRegistration());
            }
        }
    }
    return registrations.stream();
}
 
Example 16
Source File: DubboServiceMetadataRepository.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize {@link #subscribedServices the subscribed services}.
 * @return stream of subscribed services
 */
@PostConstruct
public Stream<String> initSubscribedServices() {
	Set<String> newSubscribedServices = new LinkedHashSet<>();

	// If subscribes all services
	if (ALL_DUBBO_SERVICES.equals(dubboCloudProperties.getSubscribedServices())) {
		List<String> services = discoveryClient.getServices();
		newSubscribedServices.addAll(services);
		if (logger.isWarnEnabled()) {
			logger.warn(
					"Current application will subscribe all services(size:{}) in registry, "
							+ "a lot of memory and CPU cycles may be used, "
							+ "thus it's strongly recommend you using the externalized property '{}' "
							+ "to specify the services",
					newSubscribedServices.size(), "dubbo.cloud.subscribed-services");
		}
	}
	else {
		newSubscribedServices.addAll(dubboCloudProperties.subscribedServices());
	}

	// exclude current application name
	excludeSelf(newSubscribedServices);

	// copy from subscribedServices
	Set<String> oldSubscribedServices = this.subscribedServices;

	// volatile update subscribedServices to be new one
	this.subscribedServices = newSubscribedServices;

	// dispatch SubscribedServicesChangedEvent
	dispatchEvent(new SubscribedServicesChangedEvent(this, oldSubscribedServices,
			newSubscribedServices));

	// clear old one, help GC
	oldSubscribedServices.clear();

	return newSubscribedServices.stream();
}
 
Example 17
Source File: EmployeeStreamService.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public void getListData(){
	List<String> employeeIDS =
		    Arrays.asList("23234", "353453", "22222", "5555", "676767");
	Stream<String> streamsIds = employeeIDS.stream();
	
	Set<String> candidates = new HashSet<String>();
	candidates.add("Joel");
	candidates.add("Candy");
	candidates.add("Sherwin");
	Stream<String> streamCandidates = candidates.stream();
	
}
 
Example 18
Source File: ClassScanner.java    From gadtry with Apache License 2.0 5 votes vote down vote up
public ClassScanner scan()
{
    Set<Class<?>> classSet;
    try {
        if (classLoader == null) {
            classLoader = sun.misc.VM.latestUserDefinedLoader();
        }
        classSet = scanClasses(basePackage, classLoader, errorHandler);
    }
    catch (IOException e) {
        throw new InjectorException(e);
    }

    Stream<Class<?>> classStream = classSet.stream();
    if (annotations.length > 0) {
        classStream = classStream.filter(aClass -> Stream.of(annotations).anyMatch(ann -> aClass.getAnnotation(ann) != null));
    }
    if (subclasses.length > 0) {
        classStream = classStream.filter(aClass -> Stream.of(subclasses).anyMatch(sub -> sub.isAssignableFrom(aClass)));
    }
    if (classFilter != null) {
        classStream = classStream.filter(aClass -> classFilter.apply(aClass));
    }

    classSet = classStream.collect(Collectors.toSet());
    return new ClassScanner(classSet);
}
 
Example 19
Source File: StudentListByDegreeDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static List<RegistrationWithStateForExecutionYearBean> filterResults(SearchStudentsByDegreeParametersBean searchBean,
        final Set<Registration> registrations, final ExecutionYear executionYear) {
    final List<RegistrationWithStateForExecutionYearBean> result = new ArrayList<RegistrationWithStateForExecutionYearBean>();
    Stream<Registration> registrationStream = registrations.stream();

    registrationStream = registrationStream.filter(r -> r.getLastRegistrationState(executionYear) != null);

    if (searchBean.hasAnyRegistrationProtocol()) {
        registrationStream = registrationStream.filter(r -> searchBean.getRegistrationProtocols().contains(r
                .getRegistrationProtocol()));
    }

    if (searchBean.hasAnyStudentStatuteType()) {
        registrationStream = registrationStream.filter(r -> hasStudentStatuteType(searchBean, r));
    }

    if (searchBean.hasAnyRegistrationStateTypes()) {
        registrationStream = registrationStream.filter(r -> searchBean.getRegistrationStateTypes().contains(r
                .getLastRegistrationState(executionYear).getStateType()));
    }

    if (searchBean.isIngressedInChosenYear()) {
        registrationStream = registrationStream.filter(r -> r.getIngressionYear() == executionYear);
    }

    if (searchBean.hasAnyProgramConclusion()) {
        registrationStream = registrationStream.filter(r -> hasProgramConclusion(r, searchBean
                        .isIncludeConcludedWithoutConclusionProcess(), searchBean
                        .getProgramConclusions(),
                executionYear));
    }
    if (searchBean.getActiveEnrolments()) {
        registrationStream = registrationStream.filter(r -> r.hasAnyEnrolmentsIn(executionYear));
    }

    if (searchBean.getStandaloneEnrolments()) {
        registrationStream = registrationStream.filter(r -> r.hasAnyStandaloneEnrolmentsIn(executionYear));
    }

    if (searchBean.getRegime() != null) {
        registrationStream = registrationStream.filter(r -> r.getRegimeType(executionYear) == searchBean.getRegime());
    }

    if (searchBean.getNationality() != null) {
        registrationStream = registrationStream.filter(r -> r.getPerson().getCountry() == searchBean.getNationality());
    }

    if (searchBean.getIngressionType() != null) {
        registrationStream = registrationStream.filter(r -> r.getIngressionType() == searchBean.getIngressionType());
    }

    registrationStream.forEach(r -> result.add(new RegistrationWithStateForExecutionYearBean(r, r.getLastStateType(), executionYear)));

    return result;
}
 
Example 20
Source File: CandidatesRecommenderRunner.java    From RankSys with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param users target users for which recommendations are generated
 * @param candidatesSupplier function that provide the candidate items for
 * each user
 */
public CandidatesRecommenderRunner(Set<U> users, Function<U, List<I>> candidatesSupplier) {
    super(users.stream());
    this.candidatesSupplier = candidatesSupplier;
}