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.vmware.admiral.compute.container.volume.VolumeUtil.java

/**
 * Creates additional affinity rules between container descriptions which share
 * local volumes. Each container group should be deployed on a single host.
 *//* w w  w .  j a v  a  2 s. c  om*/
public static void applyLocalNamedVolumeConstraints(Collection<ComponentDescription> componentDescriptions) {

    Map<String, ContainerVolumeDescription> volumes = filterDescriptions(ContainerVolumeDescription.class,
            componentDescriptions);

    List<String> localVolumes = volumes.values().stream().filter(v -> DEFAULT_VOLUME_DRIVER.equals(v.driver))
            .map(v -> v.name).collect(Collectors.toList());

    if (localVolumes.isEmpty()) {
        return;
    }

    Map<String, ContainerDescription> containers = filterDescriptions(ContainerDescription.class,
            componentDescriptions);

    // sort containers by local volume: each set is a group of container names
    // that share a particular local volume
    List<Set<String>> localVolumeContainers = localVolumes.stream()
            .map(v -> filterByVolume(v, containers.values())).filter(s -> !s.isEmpty())
            .collect(Collectors.toList());

    if (localVolumeContainers.isEmpty()) {
        return;
    }

    /** Merge sets of containers sharing local volumes
     *
     *  C1  C2  C3  C4  C5  C6
     *   \  /\  /   |    \  /
     *    L1  L2    L3    L4
     *
     *    Input: [C1, C2], [C2, C3], [C4], [C5, C6]
     *    Output: [C1, C2, C3], [C4], [C5, C6]
     */
    localVolumeContainers = mergeSets(localVolumeContainers);

    Map<String, List<ContainerVolumeDescription>> containerToVolumes = containers.values().stream()
            .collect(Collectors.toMap(cd -> cd.name, cd -> filterVolumes(cd, volumes.values())));

    Map<String, Integer> containerToDriverCount = containerToVolumes.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey(),
                    e -> e.getValue().stream().map(vd -> vd.driver).collect(Collectors.toSet()).size()));

    for (Set<String> s : localVolumeContainers) {
        if (s.size() > 1) {
            // find the container with highest number of required drivers
            int max = s.stream().map(cn -> containerToDriverCount.get(cn))
                    .max((vc1, vc2) -> Integer.compare(vc1, vc2)).get();
            Set<String> maxDrivers = s.stream().filter(cn -> containerToDriverCount.get(cn) == max)
                    .collect(Collectors.toSet());

            String maxCont = maxDrivers.iterator().next();
            s.remove(maxCont);
            s.stream().forEach(cn -> addAffinity(maxCont, containers.get(cn)));
        }
    }
}

From source file:com.yahoo.elide.graphql.ModelBuilder.java

/**
 * Builds a GraphQL schema.//from  w  ww.  j a va  2s .  c  o  m
 * @return The built schema.
 */
public GraphQLSchema build() {
    Set<Class<?>> allClasses = dictionary.getBindings();

    if (allClasses.isEmpty()) {
        throw new IllegalArgumentException("None of the provided classes are exported by Elide");
    }

    Set<Class<?>> rootClasses = allClasses.stream().filter(dictionary::isRoot).collect(Collectors.toSet());

    /*
     * Walk the object graph (avoiding cycles) and construct the GraphQL input object types.
     */
    dictionary.walkEntityGraph(rootClasses, this::buildInputObjectStub);
    resolveInputObjectRelationships();

    /* Construct root object */
    GraphQLObjectType.Builder root = newObject().name("__root");
    for (Class<?> clazz : rootClasses) {
        String entityName = dictionary.getJsonAliasFor(clazz);
        root.field(newFieldDefinition().name(entityName).dataFetcher(dataFetcher).argument(relationshipOpArg)
                .argument(idArgument).argument(filterArgument).argument(sortArgument)
                .argument(pageFirstArgument).argument(pageOffsetArgument)
                .argument(buildInputObjectArgument(clazz, true)).type(buildConnectionObject(clazz)));
    }

    GraphQLObjectType queryRoot = root.build();
    GraphQLObjectType mutationRoot = root.name("__mutation_root").build();

    /*
     * Walk the object graph (avoiding cycles) and construct the GraphQL output object types.
     */
    dictionary.walkEntityGraph(rootClasses, this::buildConnectionObject);

    /* Construct the schema */
    GraphQLSchema schema = GraphQLSchema.newSchema().query(queryRoot).mutation(mutationRoot)
            .build(new HashSet<>(
                    CollectionUtils.union(connectionObjectRegistry.values(), inputObjectRegistry.values())));

    return schema;
}

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());
}

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

public Set<Api> findByApplication(String application) throws TechnicalException {
    final List<ApiApplicationJpa> apiApplications = internalJpaApiApplicationRepository
            .findByApplicationName(application);

    return apiApplications.stream().map(apiApplication -> apiJpaConverter.convertTo(apiApplication.getApi()))
            .collect(Collectors.toSet());
}

From source file:com.codenvy.api.audit.server.AuditManager.java

private void printAllUsers(Path auditReport) throws ServerException {
    Page<UserImpl> currentPage = userManager.getAll(30, 0);
    do {//from   w  w w  . j  a  v  a2s . c  o  m
        //Print users with their workspaces from current page
        for (UserImpl user : currentPage.getItems()) {
            List<WorkspaceImpl> workspaces;
            try {
                workspaces = workspaceManager.getWorkspaces(user.getId());
                Set<String> workspaceIds = workspaces.stream().map(WorkspaceImpl::getId)
                        .collect(Collectors.toSet());
                //add workspaces witch are belong to user, but user doesn't have permissions for them.
                workspaceManager.getByNamespace(user.getName()).stream()
                        .filter(workspace -> !workspaceIds.contains(workspace.getId()))
                        .forEach(workspaces::add);
            } catch (ServerException exception) {
                reportPrinter.printError(
                        "Failed to receive list of related workspaces for user " + user.getId(), auditReport);
                continue;
            }
            Map<String, AbstractPermissions> wsPermissions = new HashMap<>();
            for (WorkspaceImpl workspace : workspaces) {
                try {
                    wsPermissions.put(workspace.getId(),
                            permissionsManager.get(user.getId(), DOMAIN_ID, workspace.getId()));
                } catch (NotFoundException | ConflictException ignored) {
                    //User doesn't have permissions for workspace
                }
            }
            reportPrinter.printUserInfoWithHisWorkspacesInfo(auditReport, user, workspaces, wsPermissions);
        }

    } while ((currentPage = getNextPage(currentPage)) != null);
}

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

@Override
public long hasAccessToDevice(UserVO user, String deviceGuid) {
    Set<Long> networkIds = userNetworkDao.findNetworksForUser(user.getId());
    for (Long networkId : networkIds) {
        Set<DeviceVO> devices = networkDeviceDao.findDevicesForNetwork(networkId).stream()
                .map(deviceDao::findByUUID).collect(Collectors.toSet());
        if (devices != null) {
            long guidCount = devices.stream().map(DeviceVO::getGuid).filter(g -> g.equals(deviceGuid)).count();
            if (guidCount > 0) {
                return guidCount;
            }//  www.j a  v  a 2 s.  c  om
        }
    }
    return 0L;
}

From source file:com.thinkbiganalytics.metadata.modeshape.user.JcrUserGroup.java

@Nonnull
@Override//from w w  w  . j  a  va  2 s.  c o  m
public Set<UserGroup> getContainingGroups() {
    return streamContainingGroupNodes(this.node)
            .map(node -> (UserGroup) JcrUtil.toJcrObject(node, JcrUserGroup.NODE_TYPE, JcrUserGroup.class))
            .collect(Collectors.toSet());
}

From source file:com.github.aptd.simulation.TestCLanguageLabels.java

/**
 * check package translation configuration versus property items
 */// ww w.j a va  2 s.  c o m
@Test
public void testTranslation() {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    // --- read language definitions from the configuration
    final Set<String> l_translation = Collections.unmodifiableSet(
            Arrays.stream(CCommon.configuration().getObject("translation").toString().split(","))
                    .map(i -> i.trim().toLowerCase()).collect(Collectors.toSet()));

    // --- check if a test (language resource) exists for each definied language
    final Set<String> l_translationtesting = new HashSet<>(l_translation);
    l_translationtesting.removeAll(LANGUAGEPROPERY.keySet());
    assertFalse(MessageFormat.format(
            "configuration defines {1,choice,1#translation|1<translations} {0} that {1,choice,1#is|1<are} not tested",
            l_translationtesting, l_translationtesting.size()), !l_translationtesting.isEmpty());

    // --- check unused language resource files
    final Set<String> l_translationusing = new HashSet<>(LANGUAGEPROPERY.keySet());
    l_translationusing.removeAll(l_translation);
    assertFalse(MessageFormat.format(
            "{1,choice,1#translation|1<translations} {0} {1,choice,1#is|1<are} checked, which will not be used within the package configuration",
            l_translationusing, l_translationusing.size()), !l_translationusing.isEmpty());
}

From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java

private Constructor getEventHandlerConstructor(DomainEvent event) {
    Set<Constructor> constructors = Arrays.stream(targetClass.getConstructors())
            .filter(contructor -> contructor.isAnnotationPresent(ConstructionHandler.class))
            .collect(Collectors.toSet());
    for (Constructor constructor : constructors) {
        ConstructionHandler constructionHandlerAnnotation = (ConstructionHandler) constructor
                .getAnnotation(ConstructionHandler.class);
        if (constructionHandlerAnnotation.value().equals(event.getClass())) {
            return constructor;
        }//from w  w w .j  av  a  2  s.  c  o  m
    }
    return null;
}

From source file:alfio.controller.api.support.TicketHelper.java

public List<TicketFieldConfigurationDescriptionAndValue> findTicketFieldConfigurationAndValue(int eventId,
        Ticket ticket, Locale locale) {

    List<Ticket> ticketsInReservation = ticketRepository
            .findTicketsInReservation(ticket.getTicketsReservationId());
    //WORKAROUND: we only add the additionalServiceItems related fields only if it's the _first_ ticket of the reservation
    boolean isFirstTicket = ticketsInReservation.get(0).getId() == ticket.getId();

    Map<Integer, TicketFieldDescription> descriptions = ticketFieldRepository.findTranslationsFor(locale,
            eventId);/*from  w w w  . j  a va2s. c  o m*/
    Map<String, TicketFieldValue> values = ticketFieldRepository.findAllByTicketIdGroupedByName(ticket.getId());
    Function<TicketFieldConfiguration, String> extractor = (f) -> Optional.ofNullable(values.get(f.getName()))
            .map(TicketFieldValue::getValue).orElse("");
    List<AdditionalServiceItem> additionalServiceItems = isFirstTicket
            ? additionalServiceItemRepository.findByReservationUuid(ticket.getTicketsReservationId())
            : Collections.emptyList();
    Set<Integer> additionalServiceIds = additionalServiceItems.stream()
            .map(AdditionalServiceItem::getAdditionalServiceId).collect(Collectors.toSet());
    return ticketFieldRepository
            .findAdditionalFieldsForEvent(eventId).stream().filter(f -> f.getContext() == ATTENDEE || Optional
                    .ofNullable(f.getAdditionalServiceId()).filter(additionalServiceIds::contains).isPresent())
            .map(f -> {
                int count = Math
                        .max(1, Optional
                                .ofNullable(f.getAdditionalServiceId()).map(id -> (int) additionalServiceItems
                                        .stream().filter(i -> i.getAdditionalServiceId() == id).count())
                                .orElse(1));
                return new TicketFieldConfigurationDescriptionAndValue(f,
                        descriptions.getOrDefault(f.getId(), TicketFieldDescription.MISSING_FIELD), count,
                        extractor.apply(f));
            }).collect(Collectors.toList());
}