Example usage for java.util.stream Collectors toSet

List of usage examples for java.util.stream Collectors toSet

Introduction

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

Prototype

public static <T> Collector<T, ?, Set<T>> toSet() 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Set .

Usage

From source file:com.bodybuilding.argos.discovery.ClusterListDiscovery.java

@Override
public Collection<Cluster> getCurrentClusters() {
    if (servers.isEmpty()) {
        LOG.warn("No URLs Configured, is 'turbine.clusterlist.servers' property set?");
    }// ww  w  . j  a  v  a 2 s.c  o m
    return servers.stream().flatMap(u -> getClustersFromURL(u).stream()).collect(Collectors.toSet());
}

From source file:org.n52.iceland.request.operator.RequestOperatorRepository.java

public Set<RequestOperator> getRequestOperators() {
    return this.requestOperators.entrySet().stream().filter(e -> this.activation.isActive(e.getKey()))
            .map(Entry::getValue).map(Producer::get).collect(Collectors.toSet());
}

From source file:org.fenixedu.qubdocs.ui.manage.LooseEvaluationBeanController.java

@RequestMapping(value = "/create/{scpId}", method = RequestMethod.GET)
public String create(@PathVariable("scpId") final StudentCurricularPlan studentCurricularPlan,
        final Model model) {
    model.addAttribute("studentCurricularPlan", studentCurricularPlan);
    model.addAttribute("LooseEvaluationBean_enrolment_options", studentCurricularPlan.getEnrolmentsSet());
    model.addAttribute("typeValues",
            org.fenixedu.academic.domain.EvaluationSeason.all().collect(Collectors.toSet()));

    return "fenixedu-qubdocs-reports/manage/looseevaluationbean/create";
}

From source file:de.mg.stock.server.model.Stock.java

/**
 * @return list of all day prices filled up with instant prices, in case of missing day prices
 *///  ww  w  .  ja  va 2 s . c  o m
public Set<SimpleDayPrice> getAllPricesDaily() {

    getInstantPrices().stream().forEach(ip -> logger.info(ip.toString()));

    List<SimpleDayPrice> prices = Stream
            .concat(getDayPrices().stream().map(dp -> new SimpleDayPrice(dp.getDay(), dp.getAverage())),
                    getInstantPrices().stream()
                            .map(ip -> new SimpleDayPrice(ip.getTime().toLocalDate(), ip.getAverage())))
            .collect(Collectors.toList());

    Set<SimpleDayPrice> result = prices.stream()
            .collect(Collectors.groupingBy(SimpleDayPrice::getDate, Collectors.toSet())).entrySet().stream()
            .map(e -> new SimpleDayPrice(e.getKey(),
                    (long) e.getValue().stream().mapToLong(SimpleDayPrice::getAverage).average().getAsDouble()))
            .collect(Collectors.toSet());

    return result;
}

From source file:io.kodokojo.service.redis.RedisEntityStore.java

@Override
public String addEntity(Entity entity) {
    if (entity == null) {
        throw new IllegalArgumentException("entity must be defined.");
    }//from w  ww  .  j  a va2 s .com
    if (StringUtils.isNotBlank(entity.getIdentifier())) {
        throw new IllegalArgumentException("entity had already an id.");
    }
    try (Jedis jedis = pool.getResource()) {
        String id = generateId();
        List<User> admins = IteratorUtils.toList(entity.getAdmins());
        List<User> users = IteratorUtils.toList(entity.getUsers());
        Entity entityToWrite = new Entity(id, entity.getName(), entity.isConcrete(),
                IteratorUtils.toList(entity.getProjectConfigurations()), admins, users);

        List<User> allUsers = new ArrayList<>(users);
        allUsers.addAll(admins);
        Set<String> userIds = allUsers.stream().map(User::getIdentifier).collect(Collectors.toSet());

        userIds.stream().forEach(userId -> {
            addUserToEntity(userId, id);
        });

        byte[] encryptedObject = RSAUtils.encryptObjectWithAES(key, entityToWrite);
        jedis.set(RedisUtils.aggregateKey(ENTITY_PREFIX, id), encryptedObject);
        return id;
    }
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.JCloudsProvider.java

@Override
public Set<Instance> getAllInfrastructureInstances(Infrastructure infrastructure) {
    return getComputeServiceFromInfastructure(infrastructure).listNodes().stream()
            .map(computeMetadata -> (NodeMetadataImpl) computeMetadata)
            .map(nodeMetadataImpl -> instanceCreatorFromNodeMetadata.apply(nodeMetadataImpl,
                    infrastructure.getId()))
            .collect(Collectors.toSet());
}

From source file:se.uu.it.cs.recsys.dataloader.impl.CourseSelectionLoader.java

private void parseFile(File file) throws IOException {

    try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {
        br.lines().forEach(line -> {/*from  w ww . ja v a 2  s . c  o m*/
            String[] subStrs = parseLine(line);

            final String studentId = subStrs[0].trim();
            final String courseCode = subStrs[3].trim();

            if (!isValidCourseCode(courseCode)) {
                getLogger().error("Invalid course code: {}, {}", line, file.getName());
            } else {
                if (this.origCourseSelection.containsKey(studentId)) {
                    this.origCourseSelection.get(studentId).add(courseCode);
                } else {
                    Set<String> courseSetCode = Stream.of(courseCode).collect(Collectors.toSet());

                    this.origCourseSelection.put(studentId, courseSetCode);
                }
            }
        });
    }
}

From source file:eu.itesla_project.security.SecurityAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    Path caseFile = Paths.get(line.getOptionValue("case-file"));
    Set<LimitViolationType> limitViolationTypes = line.hasOption("limit-types")
            ? Arrays.stream(line.getOptionValue("limit-types").split(",")).map(LimitViolationType::valueOf)
                    .collect(Collectors.toSet())
            : EnumSet.allOf(LimitViolationType.class);
    Path csvFile = null;/*from   w  ww.  j a  va2  s.c o  m*/
    if (line.hasOption("output-csv")) {
        csvFile = Paths.get(line.getOptionValue("output-csv"));
    }

    System.out.println("Loading network '" + caseFile + "'");

    // load network
    Network network = Importers.loadNetwork(caseFile);
    if (network == null) {
        throw new RuntimeException("Case '" + caseFile + "' not found");
    }
    network.getStateManager().allowStateMultiThreadAccess(true);

    ComponentDefaultConfig defaultConfig = new ComponentDefaultConfig();
    SecurityAnalysisFactory securityAnalysisFactory = defaultConfig
            .findFactoryImplClass(SecurityAnalysisFactory.class).newInstance();
    SecurityAnalysis securityAnalysis = securityAnalysisFactory.create(network,
            LocalComputationManager.getDefault(), 0);

    ContingenciesProviderFactory contingenciesProviderFactory = defaultConfig
            .findFactoryImplClass(ContingenciesProviderFactory.class).newInstance();
    ContingenciesProvider contingenciesProvider = contingenciesProviderFactory.create();

    // run security analysis on all N-1 lines
    SecurityAnalysisResult result = securityAnalysis.runAsync(contingenciesProvider).join();

    if (!result.getPreContingencyResult().isComputationOk()) {
        System.out.println("Pre-contingency state divergence");
    }
    LimitViolationFilter limitViolationFilter = new LimitViolationFilter(limitViolationTypes);
    if (csvFile != null) {
        System.out.println("Writing results to '" + csvFile + "'");
        CsvTableFormatterFactory csvTableFormatterFactory = new CsvTableFormatterFactory();
        Security.printPreContingencyViolations(result, Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8),
                csvTableFormatterFactory, limitViolationFilter);
        Security.printPostContingencyViolations(result,
                Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND),
                csvTableFormatterFactory, limitViolationFilter);
    } else {
        SystemOutStreamWriter soutWriter = new SystemOutStreamWriter();
        AsciiTableFormatterFactory asciiTableFormatterFactory = new AsciiTableFormatterFactory();
        Security.printPreContingencyViolations(result, soutWriter, asciiTableFormatterFactory,
                limitViolationFilter);
        Security.printPostContingencyViolations(result, soutWriter, asciiTableFormatterFactory,
                limitViolationFilter);
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.KubernetesV2SearchProvider.java

@Autowired
public KubernetesV2SearchProvider(KubernetesCacheUtils cacheUtils, KubernetesSpinnakerKindMap kindMap,
        ObjectMapper objectMapper, KubernetesResourcePropertyRegistry registry) {
    this.cacheUtils = cacheUtils;
    this.mapper = objectMapper;
    this.kindMap = kindMap;
    this.registry = registry;

    this.defaultTypes = kindMap.allKubernetesKinds().stream().map(KubernetesKind::toString)
            .collect(Collectors.toList());
    this.logicalTypes = Arrays.stream(LogicalKind.values()).map(LogicalKind::toString)
            .collect(Collectors.toSet());

    this.allCaches = new HashSet<>(defaultTypes);
    this.allCaches.addAll(logicalTypes);
}

From source file:se.uu.it.cs.recsys.constraint.solver.ModelConfigBuilder.java

private void setCreditToAdvancedId(ModelConfig instance) {
    Map<CourseCredit, Set<Integer>> map = new HashMap<>();

    Set<Course> interestedAdvancedCourseSet = this.instreatedCourseCollection.stream()
            .filter(course -> course.getLevel().getLevel().equals(CourseLevel.ADVANCED.getDBString()))
            .collect(Collectors.toSet());

    CourseFlattener.flattenToCreditAndIdSetMap(interestedAdvancedCourseSet).entrySet().stream()
            .forEach(entry -> {/*from   w  w w .j  a  v a 2  s.  c  o  m*/
                map.put(CourseCredit.ofValue(entry.getKey().getCredit().floatValue()), entry.getValue());
            });

    instance.setCreditToAdvancedId(map);
}