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:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java

private void updateStocksAndQuotesFromYahoo(Set<StockProduct> askedContent) {
    if (askedContent.isEmpty()) {
        return;/*  ww w. j ava  2  s . c o  m*/
    }

    Set<StockProduct> recentlyUpdated = askedContent.stream()
            .filter(t -> t.getLastUpdate() != null && DateUtil.isRecent(t.getLastUpdate(), 1))
            .collect(Collectors.toSet());

    if (askedContent.size() != recentlyUpdated.size()) {

        String guid = AuthenticationUtil.getPrincipal().getUsername();
        SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
        if (socialUser == null) {
            return;
        }
        String token = socialUser.getAccessToken();
        Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

        if (connection != null) {
            askedContent.removeAll(recentlyUpdated);

            Map<String, StockProduct> updatableTickers = askedContent.stream()
                    .collect(Collectors.toMap(StockProduct::getId, Function.identity()));

            List<YahooQuote> yahooQuotes = connection.getApi().financialOperations()
                    .getYahooQuotes(new ArrayList<String>(updatableTickers.keySet()), token);

            Set<StockProduct> updatableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isNotBlank(yq.getExchange()))
                    .filter(yq -> updatableTickers.get(yq.getId()) != null).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!updatableProducts.isEmpty()) {
                stockProductRepository.save(updatableProducts);
            }

            //This job below should decrease with the time
            Set<StockProduct> removableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isBlank(yq.getExchange())).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!removableProducts.isEmpty()) {
                stockProductRepository.delete(removableProducts);
            }
        }
    }
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public Set<File> getHistory() throws IOException {
    Path history = getHistoryPath();
    if (Files.exists(history)) {

        Path currentConfigArchive = getConfigurationPath(getCurrentConfigurationName());
        Predicate<Path> currentConfig = p -> {
            try {
                return Files.isSameFile(p, currentConfigArchive);
            } catch (IOException e) {
                return false;
            }// w  w w . j a v a 2  s .com
        };

        return Files.list(history).filter(currentConfig.negate()).map(Path::toFile).collect(Collectors.toSet());
    }

    return new LinkedHashSet<>();
}

From source file:io.gravitee.repository.redis.management.internal.impl.MembershipRedisRepositoryImpl.java

public Set<RedisMembership> findByUserAndReferenceType(String userId, String referenceType) {
    Set<Object> keys = redisTemplate.opsForSet().members(getMembershipByUserKey(userId, referenceType));
    List<Object> values = redisTemplate.opsForHash().multiGet(REDIS_KEY, keys);
    return values.stream().filter(Objects::nonNull)
            .map(membership -> convert(membership, RedisMembership.class)).collect(Collectors.toSet());
}

From source file:io.gravitee.repository.jdbc.JdbcApiKeyRepository.java

private Set<ApiKey> getApiKeys(List<ApiApplicationJpa> apiApplications) {
    final Set<ApiKeyJpa> apiKeys = apiApplications.stream().map(apiApplication -> apiApplication.getKey())
            .collect(Collectors.toSet());

    return apiKeyJpaConverter.convertAllTo(apiKeys);
}

From source file:com.github.fhuss.kafka.streams.cep.CEPProcessor.java

@Override
@SuppressWarnings("unchecked")
public void init(ProcessorContext context) {
    this.context = context;

    KryoSerDe kryoSerDe = new KryoSerDe();
    Set<StateStoreSupplier> stateStoreSuppliers = getDefinedStateNames(stages)
            .map(s -> getStateStoreSupplier(StateStoreProvider.getStateStoreName(queryName, s), kryoSerDe,
                    kryoSerDe, inMemory))
            .collect(Collectors.toSet());

    Serde<?> keySerde = this.context.keySerde();
    Serde<?> valSerde = this.context.valueSerde();

    TimedKeyValueSerDes<K, V> timedKeyValueSerDes = new TimedKeyValueSerDes(keySerde, valSerde);
    stateStoreSuppliers.add(getStateStoreSupplier(bufferStateStoreName, kryoSerDe,
            Serdes.serdeFrom(timedKeyValueSerDes, timedKeyValueSerDes), inMemory));

    NFASTateValueSerDe valueSerDe = new NFASTateValueSerDe(
            new ComputationStageSerDe(stages, keySerde, valSerde));
    stateStoreSuppliers.add(getStateStoreSupplier(nfaStateStoreName, kryoSerDe,
            Serdes.serdeFrom(valueSerDe, valueSerDe), inMemory));

    initializeStateStores(stateStoreSuppliers);
}

From source file:com.mpush.cache.redis.connection.RedisConnectionFactory.java

/**
 * @param poolConfig can be {@literal null}.
 * @return//www . j  ava 2s . c o  m
 * @since 1.7
 */
protected JedisCluster createCluster(List<RedisNode> servers, GenericObjectPoolConfig poolConfig) {

    Set<HostAndPort> hostAndPort = servers.stream()
            .map(redisNode -> new HostAndPort(redisNode.host, redisNode.port)).collect(Collectors.toSet());

    int redirects = 5;

    if (StringUtils.isNotEmpty(getPassword())) {
        throw new IllegalArgumentException(
                "Jedis does not support password protected Redis Cluster configurations!");
    }

    if (poolConfig != null) {
        return new JedisCluster(hostAndPort, timeout, redirects, poolConfig);
    }
    return new JedisCluster(hostAndPort, timeout, redirects, poolConfig);
}

From source file:com.vsct.dt.hesperides.indexation.search.ApplicationSearch.java

/**
 * Find an application with a name or just a part of a name.
 *
 * @param name/*from www .java  2s .  c om*/
 * @return a set of applications matching request
 */
public Set<ApplicationSearchResponse> getApplicationsLike(final String name) {
    String url = String.format("/platforms/_search?size=%1$s", SEARCH_SIZE);

    String body = TemplateContentGenerator.from(mustacheSearchByNameLike)
            .put("applicationName", name.toLowerCase()).generate();

    ElasticSearchResponse<ApplicationSearchResponse> esResponse = elasticSearchClient
            .withResponseReader(elasticSearchVsctApplicationReader).post(url, body);

    return esResponse.streamOfData().collect(Collectors.toSet());
}

From source file:org.n52.iceland.service.operator.ServiceOperatorRepository.java

public Set<String> getAllSupportedVersions() {
    return this.supportedVersions.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
}

From source file:com.devicehive.dao.riak.NetworkDaoRiakImpl.java

@Override
public List<NetworkWithUsersAndDevicesVO> getNetworksByIdsAndUsers(Long idForFiltering, Set<Long> networkdIds,
        Set<Long> permittedNetworks) {
    Set<Long> intersection = networkdIds;
    if (permittedNetworks != null) {
        intersection = networkdIds.stream().filter(permittedNetworks::contains).collect(Collectors.toSet());
    }//from  w w  w. java 2s . c o m
    Stream<NetworkWithUsersAndDevicesVO> networkStream = intersection.stream()
            .map(this::findWithUsersAndDevices).filter(Optional::isPresent).map(Optional::get);
    if (idForFiltering != null) {
        networkStream = networkStream
                .filter(n -> n.getUsers().stream().anyMatch(u -> u.getId().equals(idForFiltering)));
    }
    return networkStream.collect(Collectors.toList());
}

From source file:com.yahoo.gondola.container.ZookeeperRegistryClient.java

private Set<String> getRelatedHostIds() {
    return myHostIds.stream().map(hostId -> config.getShardIds(hostId)).flatMap(Collection::stream).distinct()
            .map(shardId -> config.getMembersInShard(shardId)).flatMap(Collection::stream)
            .map(Config.ConfigMember::getHostId).collect(Collectors.toSet());
}