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.ikanow.aleph2.analytics.services.DeduplicationEnrichmentContext.java

/** Called for every new/existing merge
 * @param id_duplicate_map/*  w w w .ja va  2  s .  c o m*/
 * @param grouping_key
 */
public void resetMutableState(final Collection<JsonNode> dups, final JsonNode grouping_key) {
    _mutable_state._id_set = dups.stream().map(j -> j.get(AnnotationBean._ID)).filter(id -> null != id)
            .collect(Collectors.toSet());

    _mutable_state._grouping_key = _json_to_grouping_key.apply(grouping_key);
    _mutable_state._num_emitted = 0;
    _mutable_state._manual_ids_to_delete = new LinkedList<JsonNode>();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.text.TokenizedTextWriter.java

/**
 * Read a file containing stopwords (one per line).
 * <p>/*from ww  w.j  av  a  2 s.com*/
 * Empty lines and lines starting with ("#") are filtered out.
 * 
 * @param f
 * @return
 * @throws IOException
 */
private static Set<String> readStopwordsFile(File f) throws IOException {
    return Files.readAllLines(f.toPath()).stream().map(String::trim).filter(l -> !l.isEmpty())
            .filter(l -> !l.startsWith("#")).map(w -> w.toLowerCase()).collect(Collectors.toSet());
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.role.JcrAbstractRoleMembership.java

@Override
public void setMemebers(UsernamePrincipal... principals) {
    Set<UsernamePrincipal> newMembers = Arrays.stream(principals).collect(Collectors.toSet());
    Set<UsernamePrincipal> oldMembers = streamUsers().collect(Collectors.toSet());

    newMembers.stream().filter(u -> !oldMembers.contains(u)).forEach(this::addMember);

    oldMembers.stream().filter(u -> !newMembers.contains(u)).forEach(this::removeMember);
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.artifact.ArtifactReplacer.java

public Set<Artifact> findAll(KubernetesManifest input) {
    DocumentContext document;/* w w  w  . j a v  a2s . c  o m*/
    try {
        document = JsonPath.using(configuration).parse(mapper.writeValueAsString(input));
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Malformed manifest", e);
    }

    return replacers.stream().map(r -> {
        try {
            return ((List<String>) mapper.convertValue(r.findAll(document), new TypeReference<List<String>>() {
            })).stream().map(s -> {
                String nameFromReference = r.getNameFromReference(s);
                String name = nameFromReference == null ? s : nameFromReference;
                if (r.namePattern == null || nameFromReference != null) {
                    return Artifact.builder().type(r.getType().toString()).reference(s).name(name).build();
                } else {
                    return null;
                }
            }).filter(Objects::nonNull);
        } catch (Exception e) {
            // This happens when a manifest isn't fully defined (e.g. not all properties are there)
            log.debug("Failure converting artifacts for {} using {} (skipping)", input.getFullResourceName(), r,
                    e);
            return Stream.<Artifact>empty();
        }
    }).flatMap(x -> x).collect(Collectors.toSet());
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTTokenServices.java

private OAuth2Request getOAuth2Request(@NotNull final JwtClaims claims)
        throws MalformedClaimException, InvalidTokenException {
    final String clientId = claims.getClaimValue("client_id", String.class);
    @SuppressWarnings("unchecked")
    final Set<String> scopes = Sets.newHashSet(claims.getClaimValue("scope", Collection.class));

    final Set<SimpleGrantedAuthority> authorities = scopes.stream().map(scope -> {
        if (scope.startsWith(GENIE_SCOPE_PREFIX)) {
            scope = scope.substring(GENIE_SCOPE_PREFIX_LENGTH);
        }//  w  ww. ja  v a 2 s.  co m

        return new SimpleGrantedAuthority(ROLE + scope.toUpperCase());
    }).collect(Collectors.toSet());

    if (authorities.isEmpty()) {
        throw new InvalidTokenException("No scopes found. Unable to authorize");
    }

    // Assume a user is a subset of admin so always grant admin user the role user as well
    if (authorities.contains(ADMIN)) {
        authorities.add(USER);
    }

    return new OAuth2Request(null, clientId, authorities, true, scopes, null, null, null, null);
}

From source file:com.uber.hoodie.hadoop.realtime.AbstractRealtimeRecordReader.java

/**
 * Given a comma separated list of field names and positions at which they appear on Hive, return
 * a ordered list of field names, that can be passed onto storage.
 *//*  ww  w .j a  v  a 2  s .  c  om*/
public static List<String> orderFields(String fieldNameCsv, String fieldOrderCsv,
        String partitioningFieldsCsv) {

    String[] fieldOrders = fieldOrderCsv.split(",");
    Set<String> partitioningFields = Arrays.stream(partitioningFieldsCsv.split(","))
            .collect(Collectors.toSet());
    List<String> fieldNames = Arrays.stream(fieldNameCsv.split(","))
            .filter(fn -> !partitioningFields.contains(fn)).collect(Collectors.toList());

    // Hive does not provide ids for partitioning fields, so check for lengths excluding that.
    if (fieldNames.size() != fieldOrders.length) {
        throw new HoodieException(
                String.format("Error ordering fields for storage read. #fieldNames: %d, #fieldPositions: %d",
                        fieldNames.size(), fieldOrders.length));
    }
    TreeMap<Integer, String> orderedFieldMap = new TreeMap<>();
    for (int ox = 0; ox < fieldOrders.length; ox++) {
        orderedFieldMap.put(Integer.parseInt(fieldOrders[ox]), fieldNames.get(ox));
    }
    return new ArrayList<>(orderedFieldMap.values());
}

From source file:com.carlomicieli.jtrains.value.objects.LocalizedField.java

/**
 * Returns the {@code Set} of the {@code Locale}s used in the current field.
 * @return the {@code Locale}s set/*  ww  w. jav a2 s  . c om*/
 */
public Set<Locale> locales() {
    return this.values.keySet().stream().map(LocalizedField::localeFromKey).collect(Collectors.toSet());
}

From source file:bjerne.gallery.service.impl.GalleryAuthorizationServiceSSImpl.java

private Collection<String> getCurrentUserRoles() {
    Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
            .getAuthorities();//  ww w  .jav a2 s . c  o  m
    Collection<String> currentUserRoles = authorities.stream().map(e -> e.getAuthority())
            .collect(Collectors.toSet());
    LOG.debug("Roles for current user: {}", currentUserRoles);
    return currentUserRoles;
}

From source file:me.rkfg.xmpp.bot.plugins.FaggotOfTheDayPlugin.java

private Set<Occupant> getAllOccupants(MultiUserChat muc) {
    return muc.getOccupants().stream().map(muc::getOccupant)
            .filter(occupant -> !occupant.getNick().equals(getBotNick())).collect(Collectors.toSet());
}

From source file:io.gravitee.management.service.impl.ApplicationServiceImpl.java

@Override
public Set<ApplicationEntity> findAll() {
    try {//from   w w  w . j av  a2s.  co m
        LOGGER.debug("Find all applications");

        final Set<Application> applications = applicationRepository.findAll();

        if (applications == null || applications.isEmpty()) {
            return emptySet();
        }

        final Set<ApplicationEntity> applicationEntities = new HashSet<>(applications.size());

        applicationEntities
                .addAll(applications.stream().map(ApplicationServiceImpl::convert).collect(Collectors.toSet()));

        return applicationEntities;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find all applications", ex);
        throw new TechnicalManagementException("An error occurs while trying to find all applications", ex);
    }
}