Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:nu.yona.server.device.service.DeviceService.java

@Transactional
public void removeDuplicateDefaultDevices(UserDto userDto, UUID requestingDeviceId) {
    userService.updateUser(userDto.getId(), userEntity -> {
        Set<UserDevice> defaultDevices = userEntity.getDevices().stream()
                .filter(d -> d.getDeviceAnonymized().getDeviceIndex() == 0).collect(Collectors.toSet());
        if (defaultDevices.isEmpty()) {
            throw DeviceServiceException.noDevicesFound(userEntity.getUserAnonymizedId());
        }//from   ww  w .j  ava2s.c o m
        if (defaultDevices.size() == 1) {
            // User is in good shape
            return;
        }
        UserDevice requestingDevice = userEntity.getDevices().stream()
                .filter(d -> d.getId().equals(requestingDeviceId)).findFirst()
                .orElseThrow(() -> DeviceServiceException.notFoundById(requestingDeviceId));
        defaultDevices.stream().filter(d -> d != requestingDevice)
                .forEach(d -> removeDuplicateDefaultDevice(userEntity, requestingDevice, d));
        userAnonymizedService.updateUserAnonymized(userEntity.getAnonymized().getId());
    });
}

From source file:net.dv8tion.jda.core.entities.EntityBuilder.java

private Map<String, AuditLogChange> changeToMap(Set<AuditLogChange> changesList) {
    return changesList.stream().collect(Collectors.toMap(AuditLogChange::getKey, UnaryOperator.identity()));
}

From source file:com.netflix.spinnaker.front50.model.S3Support.java

/**
 * Fetch any previously cached applications that have been updated since last retrieved.
 *
 * @param existingItems Previously cached applications
 * @return Refreshed applications//ww w.j  av a  2 s.c o  m
 */
protected Set<T> fetchAllItems(Set<T> existingItems) {
    if (existingItems == null) {
        existingItems = new HashSet<>();
    }

    Long refreshTime = System.currentTimeMillis();

    ObjectListing bucketListing = amazonS3
            .listObjects(new ListObjectsRequest(bucket, rootFolder, null, null, 10000));
    List<S3ObjectSummary> summaries = bucketListing.getObjectSummaries();

    while (bucketListing.isTruncated()) {
        bucketListing = amazonS3.listNextBatchOfObjects(bucketListing);
        summaries.addAll(bucketListing.getObjectSummaries());
    }

    Map<String, S3ObjectSummary> summariesByName = summaries.stream().filter(this::filterS3ObjectSummary)
            .collect(Collectors.toMap(S3ObjectSummary::getKey, Function.identity()));

    Map<String, T> existingItemsByName = existingItems.stream()
            .filter(a -> summariesByName.containsKey(buildS3Key(a)))
            .collect(Collectors.toMap(Timestamped::getId, Function.identity()));

    summaries = summariesByName.values().stream().filter(s3ObjectSummary -> {
        String itemName = extractItemName(s3ObjectSummary);
        T existingItem = existingItemsByName.get(itemName);

        return existingItem == null || existingItem.getLastModified() == null
                || s3ObjectSummary.getLastModified().after(new Date(existingItem.getLastModified()));
    }).collect(Collectors.toList());

    Observable.from(summaries).buffer(10).flatMap(ids -> Observable.from(ids).flatMap(s3ObjectSummary -> {
        try {
            return Observable
                    .just(amazonS3.getObject(s3ObjectSummary.getBucketName(), s3ObjectSummary.getKey()));
        } catch (AmazonS3Exception e) {
            if (e.getStatusCode() == 404) {
                // an item has been removed between the time that object summaries were fetched and now
                existingItemsByName.remove(extractItemName(s3ObjectSummary));
                return Observable.empty();
            }

            throw e;
        }
    }).subscribeOn(scheduler)).map(s3Object -> {
        try {
            T item = deserialize(s3Object);
            item.setLastModified(s3Object.getObjectMetadata().getLastModified().getTime());
            return item;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }).subscribeOn(scheduler).toList().toBlocking().single().forEach(item -> {
        existingItemsByName.put(item.getId().toLowerCase(), item);
    });

    existingItems = existingItemsByName.values().stream().collect(Collectors.toSet());
    this.lastRefreshedTime = refreshTime;
    return existingItems;
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private AdditionalData<Name, Change> createChangesByNameAdditionalData() {
    // Which names area we interested in?
    List<Change> selectedChanges = changesTableView.getItems();

    List<Name> names = selectedChanges.stream().flatMap(ch -> {
        Set<Name> allNames = ch.getAllNames();
        List<Name> binomials = allNames.stream().flatMap(n -> n.asBinomial()).collect(Collectors.toList());
        List<Name> genus = allNames.stream().flatMap(n -> n.asGenus()).collect(Collectors.toList());

        allNames.addAll(binomials);/* w  ww.j  av a  2 s . c  o m*/
        allNames.addAll(genus);

        return allNames.stream();
    }).distinct().sorted().collect(Collectors.toList());

    Project proj = datasetView.getProjectView().getProject();

    Map<Name, List<Change>> map = new HashMap<>();
    for (Name n : names) {
        map.put(n, proj.getDatasets().stream().flatMap(ds -> ds.getAllChanges())
                .filter(ch -> ch.getAllNames().contains(n)).collect(Collectors.toList()));
    }

    List<TableColumn<Change, String>> cols = new ArrayList<>();

    cols.add(getChangeTableColumn("Dataset", ch -> ch.getDataset().toString()));
    cols.add(getChangeTableColumn("Type", ch -> ch.getType().toString()));
    cols.add(getChangeTableColumn("From", ch -> ch.getFrom().toString()));
    cols.add(getChangeTableColumn("To", ch -> ch.getTo().toString()));
    cols.add(getChangeTableColumn("Note", ch -> ch.getNote().orElse("")));

    return new AdditionalData<Name, Change>("Changes by name", names, map, cols,
            changes -> changes.stream().flatMap(ch -> ch.getAllNames().stream()).collect(Collectors.toList()));
}

From source file:ddf.catalog.impl.operations.QueryOperations.java

@Nullable
protected Filter getNonVersionTagsFilter(Operation requestOperation) {
    FilterBuilder filterBuilder = frameworkProperties.getFilterBuilder();
    if (requestOperation.containsPropertyName("operation.query-tags")) {
        Set<String> queryTags = Optional.of(requestOperation)
                .map((ro) -> ro.getPropertyValue("operation.query-tags")).filter(Set.class::isInstance)
                .map(Set.class::cast).orElse(Collections.emptySet());
        if (queryTags.isEmpty()) {
            return null;
        }/*  www.j  a  va2 s  . co  m*/
        return filterBuilder.anyOf(
                queryTags.stream().map(tag -> filterBuilder.attribute(Metacard.TAGS).is().like().text(tag))
                        .collect(Collectors.toList()));
    }
    return filterBuilder.not(filterBuilder.anyOf(
            filterBuilder.attribute(Metacard.TAGS).is().like().text(MetacardVersion.VERSION_TAG),
            filterBuilder.attribute(Metacard.TAGS).is().like().text(DeletedMetacard.DELETED_TAG)));
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private AdditionalData<Name, Map.Entry<String, String>> createDataByNameAdditionalData() {
    // Which names area we interested in?
    List<Change> selectedChanges = changesTableView.getItems();

    List<Name> names = selectedChanges.stream().flatMap(ch -> {
        Set<Name> allNames = ch.getAllNames();
        List<Name> binomials = allNames.stream().flatMap(n -> n.asBinomial()).collect(Collectors.toList());
        List<Name> genus = allNames.stream().flatMap(n -> n.asGenus()).collect(Collectors.toList());

        allNames.addAll(binomials);//w  w w.  j  a  va2 s. c  o  m
        allNames.addAll(genus);

        return allNames.stream();
    }).distinct().sorted().collect(Collectors.toList());

    Project proj = datasetView.getProjectView().getProject();

    Map<Name, List<Map.Entry<String, String>>> map = new HashMap<>();
    for (Name n : names) {
        Map<DatasetColumn, Set<String>> dataForName = proj.getDataForName(n);
        Map<String, String> mapForName = dataForName.entrySet().stream()
                .collect(Collectors.toMap(
                        (Map.Entry<DatasetColumn, Set<String>> entry) -> entry.getKey().toString(),
                        (Map.Entry<DatasetColumn, Set<String>> entry) -> entry.getValue().toString()));
        map.put(n, new ArrayList<>(mapForName.entrySet()));
    }

    List<TableColumn<Map.Entry<String, String>, String>> cols = new ArrayList<>();

    TableColumn<Map.Entry<String, String>, String> colKey = new TableColumn<>("Key");
    colKey.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getKey()));
    cols.add(colKey);

    TableColumn<Map.Entry<String, String>, String> colValue = new TableColumn<>("Value");
    colValue.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
    cols.add(colValue);

    return new AdditionalData<Name, Map.Entry<String, String>>("Data by name", names, map, cols,
            changes -> changes.stream().flatMap(ch -> ch.getAllNames().stream()).collect(Collectors.toList()));
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private AdditionalData<Name, Change> createChangesBySubnamesAdditionalData() {
    // Which names area we interested in?
    List<Change> selectedChanges = changesTableView.getItems();

    List<Name> names = selectedChanges.stream().flatMap(ch -> {
        Set<Name> allNames = ch.getAllNames();
        List<Name> binomials = allNames.stream().flatMap(n -> n.asBinomial()).collect(Collectors.toList());
        List<Name> genus = allNames.stream().flatMap(n -> n.asGenus()).collect(Collectors.toList());

        allNames.addAll(binomials);/* www. j a v  a 2  s .  c  o  m*/
        allNames.addAll(genus);

        return allNames.stream();
    }).distinct().sorted().collect(Collectors.toList());

    Project proj = datasetView.getProjectView().getProject();

    Map<Name, List<Change>> map = new HashMap<>();
    for (Name query : names) {
        map.put(query,
                proj.getDatasets().stream().flatMap(ds -> ds.getAllChanges())
                        .filter(ch -> ch.getAllNames().contains(query)
                                || ch.getAllNames().stream().flatMap(n -> n.asBinomial())
                                        .anyMatch(binomial -> query.equals(binomial))
                                || ch.getAllNames().stream().flatMap(n -> n.asGenus())
                                        .anyMatch(genus -> query.equals(genus)))
                        .collect(Collectors.toList()));
    }

    List<TableColumn<Change, String>> cols = new ArrayList<>();

    cols.add(getChangeTableColumn("Dataset", ch -> ch.getDataset().toString()));
    cols.add(getChangeTableColumn("Type", ch -> ch.getType().toString()));
    cols.add(getChangeTableColumn("From", ch -> ch.getFrom().toString()));
    cols.add(getChangeTableColumn("To", ch -> ch.getTo().toString()));
    cols.add(getChangeTableColumn("Note", ch -> ch.getNote().orElse("")));

    return new AdditionalData<Name, Change>("Changes by subname", names, map, cols,
            changes -> changes.stream().flatMap(ch -> ch.getAllNames().stream()).collect(Collectors.toList()));
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public Collection<String> allCubeIds() {

    Set<Member> members = hazelcastInstance.getCluster().getMembers();
    // Exact match
    return members.stream().filter(e -> e.getStringAttribute("cubeId") != null)
            .map(e -> e.getStringAttribute("cubeId")).collect(Collectors.toList());
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public Collection<String> cubeIds(String cubeDate) {

    Set<Member> members = hazelcastInstance.getCluster().getMembers();
    // Exact match
    return members.stream().filter(e -> e.getStringAttribute("cubeId").split("::")[0].startsWith(cubeDate))
            .map(e -> e.getStringAttribute("cubeId")).collect(Collectors.toList());
}

From source file:net.dv8tion.jda.core.managers.GuildController.java

/**
 * Modifies the {@link net.dv8tion.jda.core.entities.Role Roles} of the specified {@link net.dv8tion.jda.core.entities.Member Member}
 * by adding and removing a collection of roles.
 * <br>None of the provided roles may be the <u>Public Role</u> of the current Guild.
 * <br>If a role is both in {@code rolesToAdd} and {@code rolesToRemove} it will be removed.
 *
 * <p>None of the provided collections may be null
 * <br>To only add or remove roles use either {@link #removeRolesFromMember(Member, Collection)} or {@link #addRolesToMember(Member, Collection)}
 *
 * <h1>Warning</h1>/*from  w w w  .  j a  va  2s. co m*/
 * <b>This may <u>not</u> be used together with any other role add/remove/modify methods for the same Member
 * within one event listener cycle! The changes made by this require cache updates which are triggered by
 * lifecycle events which are received later. This may only be called again once the specific Member has been updated
 * by a {@link net.dv8tion.jda.core.events.guild.member.GenericGuildMemberEvent GenericGuildMemberEvent} targeting the same Member.</b>
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} caused by
 * the returned {@link net.dv8tion.jda.core.requests.RestAction RestAction} include the following:
 * <ul>
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The Members Roles could not be modified due to a permission discrepancy</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>We were removed from the Guild before finishing the task</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MEMBER UNKNOWN_MEMBER}
 *     <br>The target Member was removed from the Guild before finishing the task</li>
 * </ul>
 *
 * @param  member
 *         The {@link net.dv8tion.jda.core.entities.Member Member} that should be modified
 * @param  rolesToAdd
 *         A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles}
 *         to add to the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has
 * @param  rolesToRemove
 *         A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles}
 *         to remove from the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has
 *
 * @throws net.dv8tion.jda.core.exceptions.GuildUnavailableException
 *         If the guild is temporarily not {@link net.dv8tion.jda.core.entities.Guild#isAvailable() available}
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the provided roles are higher in the Guild's hierarchy
 *         and thus cannot be modified by the currently logged in account
 * @throws IllegalArgumentException
 *         <ul>
 *             <li>If any of the provided arguments is {@code null}</li>
 *             <li>If any of the specified Roles is managed or is the {@code Public Role} of the Guild</li>
 *         </ul>
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction}
 */
@CheckReturnValue
public AuditableRestAction<Void> modifyMemberRoles(Member member, Collection<Role> rolesToAdd,
        Collection<Role> rolesToRemove) {
    checkAvailable();
    Checks.notNull(member, "member");
    Checks.notNull(rolesToAdd, "Collection containing roles to be added to the member");
    Checks.notNull(rolesToRemove, "Collection containing roles to be removed from the member");
    checkGuild(member.getGuild(), "member");
    checkPermission(Permission.MANAGE_ROLES);
    rolesToAdd.forEach(role -> {
        Checks.notNull(role, "role in rolesToAdd");
        checkGuild(role.getGuild(), "role: " + role.toString());
        checkPosition(role);
        if (role.isManaged())
            throw new IllegalArgumentException(
                    "Cannot add a Managed role to a Member. Role: " + role.toString());
    });
    rolesToRemove.forEach(role -> {
        Checks.notNull(role, "role in rolesToRemove");
        checkGuild(role.getGuild(), "role: " + role.toString());
        checkPosition(role);
        if (role.isManaged())
            throw new IllegalArgumentException(
                    "Cannot remove a Managed role from a Member. Role: " + role.toString());
    });

    Set<Role> currentRoles = new HashSet<>(((MemberImpl) member).getRoleSet());
    currentRoles.addAll(rolesToAdd);
    currentRoles.removeAll(rolesToRemove);

    if (currentRoles.contains(guild.getPublicRole()))
        throw new IllegalArgumentException(
                "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!");

    JSONObject body = new JSONObject().put("roles",
            currentRoles.stream().map(Role::getId).collect(Collectors.toList()));
    Route.CompiledRoute route = Route.Guilds.MODIFY_MEMBER.compile(guild.getId(), member.getUser().getId());

    return new AuditableRestAction<Void>(guild.getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (response.isOk())
                request.onSuccess(null);
            else
                request.onFailure(response);
        }
    };
}