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.vsct.dt.hesperides.resources.Properties.java

/**
 * Copy all properties without empty values
 *
 * @return the copy of the properties// www .ja  v  a2 s .  c om
 */
public Properties makeCopyWithoutNullOrEmptyValorisations() {

    // For key value properties
    Set<KeyValueValorisation> keyValuePropertiesCleaned = this.keyValueProperties.stream()
            .filter(kvp -> kvp.getValue() != null && !kvp.getValue().isEmpty()).collect(Collectors.toSet());

    // For iterable properties
    Set<IterableValorisation> iterablePropertiesCleaned = Sets.newHashSet();

    for (Valorisation val : this.iterableProperties) {
        iterablePropertiesCleaned.add(copyIterableValorisation((IterableValorisation) val));
    }

    // cleaned
    return new Properties(keyValuePropertiesCleaned, iterablePropertiesCleaned);
}

From source file:com.epam.ta.reportportal.ws.resolver.FilterCriteriaResolver.java

@SuppressWarnings("unchecked")
private <T> Filter resolveAsList(MethodParameter methodParameter, NativeWebRequest webRequest) {
    Class<T> domainModelType = (Class<T>) methodParameter.getParameterAnnotation(FilterFor.class).value();

    Set<FilterCondition> filterConditions = webRequest.getParameterMap().entrySet().stream()
            .filter(parameter -> parameter.getKey().startsWith(DEFAULT_FILTER_PREFIX)
                    && parameter.getValue().length > 0)
            .map(parameter -> {/*  w  w w . java2  s.c om*/
                final String[] tokens = parameter.getKey().split("\\.");
                checkTokens(tokens);
                String stringCondition = tokens[1];
                boolean isNegative = stringCondition.startsWith(NOT_FILTER_MARKER);

                Condition condition = getCondition(
                        isNegative ? StringUtils.substringAfter(stringCondition, NOT_FILTER_MARKER)
                                : stringCondition);
                String criteria = tokens[2];
                return new FilterCondition(condition, isNegative, parameter.getValue()[0], criteria);

            }).collect(Collectors.toSet());
    return new Filter(domainModelType, filterConditions);
}

From source file:uk.ac.kcl.at.ElasticGazetteerAcceptanceTest.java

@Test
public void deidentificationPerformanceTest() {
    dbmsTestUtils.createBasicInputTable();
    dbmsTestUtils.createBasicOutputTable();
    dbmsTestUtils.createDeIdInputTable();
    List<Mutant> mutants = testUtils.insertTestDataForDeidentification(env.getProperty("tblIdentifiers"),
            env.getProperty("tblInputDocs"), mutatortype, true);

    int totalTruePositives = 0;
    int totalFalsePositives = 0;
    int totalFalseNegatives = 0;

    for (Mutant mutant : mutants) {
        Set<Pattern> mutatedPatterns = new HashSet<>();
        mutant.setDeidentifiedString(elasticGazetteerService.deIdentifyString(mutant.getFinalText(),
                String.valueOf(mutant.getDocumentid())));
        Set<String> set = new HashSet<>(mutant.getOutputTokens());
        mutatedPatterns.addAll(//from  www .jav  a2  s .co  m
                set.stream().map(string -> Pattern.compile(Pattern.quote(string), Pattern.CASE_INSENSITIVE))
                        .collect(Collectors.toSet()));
        List<MatchResult> results = new ArrayList<>();
        for (Pattern pattern : mutatedPatterns) {
            Matcher matcher = pattern.matcher(mutant.getFinalText());
            while (matcher.find()) {
                results.add(matcher.toMatchResult());
            }
        }

        int truePositives = getTruePositiveTokenCount(mutant);
        int falsePositives = getFalsePositiveTokenCount(mutant);
        int falseNegatives = getFalseNegativeTokenCount(mutant);

        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                + " inaccurately masked tokens from a total of " + (falsePositives + truePositives));
        System.out.println("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
        System.out.println("Doc ID precision " + calcPrecision(falsePositives, truePositives));
        System.out.println("Doc ID recall " + calcRecall(falseNegatives, truePositives));
        System.out.println(mutant.getDeidentifiedString());
        System.out.println(mutant.getFinalText());
        System.out.println(mutant.getInputTokens());
        System.out.println(mutant.getOutputTokens());
        System.out.println();
        if (env.getProperty("elasticgazetteerTestOutput") != null) {
            try {
                try (BufferedWriter bw = new BufferedWriter(
                        new FileWriter(new File(env.getProperty("elasticgazetteerTestOutput") + File.separator
                                + mutant.getDocumentid())))) {
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                            + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
                    bw.newLine();
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                            + " inaccurately masked tokens from a total of "
                            + (falsePositives + truePositives));
                    bw.newLine();
                    bw.write("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
                    bw.newLine();
                    bw.write("Doc ID precision " + calcPrecision(falsePositives, truePositives));
                    bw.newLine();
                    bw.write("Doc ID recall " + calcRecall(falseNegatives, truePositives));
                    bw.newLine();
                    bw.write(mutant.getDeidentifiedString());
                    bw.newLine();
                    bw.write(mutant.getFinalText());
                    bw.newLine();
                    bw.write(mutant.getInputTokens().toString());
                    bw.newLine();
                    bw.write(mutant.getOutputTokens().toString());

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        totalTruePositives += truePositives;
        totalFalsePositives += falsePositives;
        totalFalseNegatives += falseNegatives;
    }
    DecimalFormat df = new DecimalFormat("#.#");
    df.setRoundingMode(RoundingMode.CEILING);

    System.out.println();
    System.out.println();
    System.out.println("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
            + totalFalseNegatives);
    System.out.println("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
    System.out.println("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
    System.out.println(totalTruePositives + " & " + totalFalsePositives + " & " + totalFalseNegatives + " & "
            + df.format(calcPrecision(totalFalsePositives, totalTruePositives)) + " & "
            + df.format(calcRecall(totalFalseNegatives, totalTruePositives)) + " \\\\");

    if (env.getProperty("elasticgazetteerTestOutput") != null) {
        try {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(
                    new File(env.getProperty("elasticgazetteerTestOutput") + File.separator + "summary")))) {
                bw.write("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
                        + totalFalseNegatives);
                bw.newLine();
                bw.write("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
                bw.newLine();
                bw.write("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.appsolve.padelcampus.controller.events.EventsBookingController.java

@RequestMapping(method = GET, value = "/{eventId}/participate")
public ModelAndView participate(@PathVariable("eventId") Long eventId, HttpServletRequest request) {
    Player user = sessionUtil.getUser(request);
    if (user == null) {
        return getLoginRequiredView(request, msg.get("Participate"));
    }//from   w  ww  . j a v  a2s  .c  o m
    Event event = eventDAO.findById(eventId);
    EventBookingRequest eventBookingRequest = new EventBookingRequest();
    if (event.getEventType().equals(EventType.CommunityRoundRobin)) {
        Integer maxNumberOfNewPlayers = Math.max(0,
                event.getMaxNumberOfParticipants() - event.getParticipants().size());
        List<Player> newPlayers = new ArrayList<>();
        for (int i = 0; i < maxNumberOfNewPlayers; i++) {
            newPlayers.add(new Player());
        }
        eventBookingRequest.setNewPlayers(newPlayers);
        eventBookingRequest.setPlayers(Stream.of(user).collect(Collectors.toSet()));
    }
    return participateView(eventId, eventBookingRequest);
}

From source file:com.publictransitanalytics.scoregenerator.output.ComparativeNetworkAccessibility.java

public ComparativeNetworkAccessibility(final int taskCount, final int trialTaskCount, final ScoreCard scoreCard,
        final ScoreCard trialScoreCard, final Grid grid, final Set<Sector> centerSectors,
        final LocalDateTime startTime, final LocalDateTime endTime, final LocalDateTime trialStartTime,
        final LocalDateTime trialEndTime, final Duration tripDuration, final Duration samplingInterval,
        final boolean backward, final String trialName, final Duration inServiceTime,
        final Duration trialInServiceTime) throws InterruptedException {
    type = AccessibilityType.COMPARATIVE_NETWORK_ACCESSIBILITY;

    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    boundsCenter = new Point(grid.getBounds().getCenter());
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialStartTime = trialStartTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialEndTime = trialEndTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;
    this.trialTaskCount = trialTaskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, CountComparison> countBuilder = ImmutableMap.builder();
    for (final Sector sector : sectors) {
        final int count = scoreCard.hasPath(sector) ? scoreCard.getReachedCount(sector) : 0;
        final int trialCount = trialScoreCard.hasPath(sector) ? trialScoreCard.getReachedCount(sector) : 0;

        if (count != 0 && trialCount != 0) {
            final Bounds bounds = new Bounds(sector);
            final CountComparison comparison = new CountComparison(count, trialCount);
            countBuilder.put(bounds, comparison);
        }/* w  w  w  .  j  a  va2 s .  c  o m*/
    }

    sectorCounts = countBuilder.build();

    this.centerPoints = centerSectors.stream().map(sector -> new Point(sector.getBounds().getCenter()))
            .collect(Collectors.toSet());
    sampleCount = centerPoints.size();

    this.trialName = trialName;

    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

From source file:io.kodokojo.endpoint.ProjectSparkEndpoint.java

@Override
public void configure() {
    post(BASE_API + "/projectconfig", JSON_CONTENT_TYPE, (request, response) -> {
        String body = request.body();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Try to create project {}", body);
        }/* ww  w .java2s .  c om*/
        Gson gson = localGson.get();
        ProjectCreationDto dto = gson.fromJson(body, ProjectCreationDto.class);
        if (dto == null) {
            halt(400);
            return "";
        }
        User owner = userStore.getUserByIdentifier(dto.getOwnerIdentifier());
        String entityId = owner.getEntityIdentifier();
        if (StringUtils.isBlank(entityId)) {
            halt(400);
            return "";
        }

        Set<StackConfiguration> stackConfigurations = createDefaultStackConfiguration(dto.getName());
        if (CollectionUtils.isNotEmpty(dto.getStackConfigs())) {
            stackConfigurations = dto.getStackConfigs().stream().map(stack -> {
                Set<BrickConfiguration> brickConfigurations = stack.getBrickConfigs().stream().map(b -> {
                    Brick brick = brickFactory.createBrick(b.getName());
                    return new BrickConfiguration(brick);
                }).collect(Collectors.toSet());
                StackType stackType = StackType.valueOf(stack.getType());
                BootstrapStackData bootstrapStackData = projectManager.bootstrapStack(dto.getName(),
                        stack.getName(), stackType);
                return new StackConfiguration(stack.getName(), stackType, brickConfigurations,
                        bootstrapStackData.getLoadBalancerHost(), bootstrapStackData.getSshPort());
            }).collect(Collectors.toSet());
        }

        List<User> users = new ArrayList<>();
        users.add(owner);
        if (CollectionUtils.isNotEmpty(dto.getUserIdentifiers())) {
            for (String userId : dto.getUserIdentifiers()) {
                User user = userStore.getUserByIdentifier(userId);
                users.add(user);
            }
        }
        ProjectConfiguration projectConfiguration = new ProjectConfiguration(entityId, dto.getName(),
                Collections.singletonList(owner), stackConfigurations, users);
        String projectConfigIdentifier = projectStore.addProjectConfiguration(projectConfiguration);

        response.status(201);
        response.header("Location", "/projectconfig/" + projectConfigIdentifier);
        return projectConfigIdentifier;
    });

    get(BASE_API + "/projectconfig/:id", JSON_CONTENT_TYPE, (request, response) -> {
        String identifier = request.params(":id");
        ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
        if (projectConfiguration == null) {
            halt(404);
            return "";
        }
        SimpleCredential credential = extractCredential(request);
        if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
            return new ProjectConfigDto(projectConfiguration);
        }
        halt(403);
        return "";
    }, jsonResponseTransformer);

    put(BASE_API + "/projectconfig/:id/user", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);

        String identifier = request.params(":id");
        ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
        if (projectConfiguration == null) {
            halt(404);
            return "";
        }
        if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
            JsonParser parser = new JsonParser();
            JsonArray root = (JsonArray) parser.parse(request.body());
            List<User> users = IteratorUtils.toList(projectConfiguration.getUsers());
            List<User> usersToAdd = new ArrayList<>();
            for (JsonElement el : root) {
                String userToAddId = el.getAsJsonPrimitive().getAsString();
                User userToAdd = userStore.getUserByIdentifier(userToAddId);
                if (userToAdd != null && !users.contains(userToAdd)) {
                    users.add(userToAdd);
                    usersToAdd.add(userToAdd);
                }
            }

            projectConfiguration.setUsers(users);
            projectStore.updateProjectConfiguration(projectConfiguration);
            projectManager.addUsersToProject(projectConfiguration, usersToAdd);
        } else {
            halt(403, "You have not right to add user to project configuration id " + identifier + ".");
        }

        return "";
    }), jsonResponseTransformer);

    delete(BASE_API + "/projectconfig/:id/user", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            String identifier = request.params(":id");
            ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
            if (projectConfiguration == null) {
                halt(404);
                return "";
            }
            if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
                JsonParser parser = new JsonParser();
                JsonArray root = (JsonArray) parser.parse(request.body());
                List<User> users = IteratorUtils.toList(projectConfiguration.getUsers());
                for (JsonElement el : root) {
                    String userToDeleteId = el.getAsJsonPrimitive().getAsString();
                    User userToDelete = userStore.getUserByIdentifier(userToDeleteId);
                    if (userToDelete != null) {
                        users.remove(userToDelete);
                    }
                }
                projectConfiguration.setUsers(users);
                projectStore.updateProjectConfiguration(projectConfiguration);
            } else {
                halt(403, "You have not right to delete user to project configuration id " + identifier + ".");
            }
        }
        return "";
    }), jsonResponseTransformer);

    //  -- Project

    //  Start project
    post(BASE_API + "/project/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User currentUser = userStore.getUserByUsername(credential.getUsername());
            String projectConfigurationId = request.params(":id");
            ProjectConfiguration projectConfiguration = projectStore
                    .getProjectConfigurationById(projectConfigurationId);
            if (projectConfiguration == null) {
                halt(404, "Project configuration not found.");
                return "";
            }
            if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
                String projectId = projectStore.getProjectIdByProjectConfigurationId(projectConfigurationId);
                if (StringUtils.isBlank(projectId)) {
                    //   projectManager.bootstrapStack(projectConfiguration.getName(), projectConfiguration.getDefaultStackConfiguration().getName(), projectConfiguration.getDefaultStackConfiguration().getType());
                    Project project = projectManager.start(projectConfiguration);
                    response.status(201);
                    String projectIdStarted = projectStore.addProject(project, projectConfigurationId);
                    return projectIdStarted;
                } else {
                    halt(409, "Project already exist.");
                }
            } else {
                halt(403,
                        "You have not right to start project configuration id " + projectConfigurationId + ".");
            }
        }
        return "";
    }));

    get(BASE_API + "/project/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User currentUser = userStore.getUserByUsername(credential.getUsername());
            String projectId = request.params(":id");
            Project project = projectStore.getProjectByIdentifier(projectId);
            if (project == null) {
                halt(404);
                return "";
            }
            ProjectConfiguration projectConfiguration = projectStore
                    .getProjectConfigurationById(project.getProjectConfigurationIdentifier());
            if (userStore.userIsAdminOfProjectConfiguration(currentUser.getUsername(), projectConfiguration)) {
                return new ProjectDto(project);
            } else {
                halt(403, "You have not right to lookup project id " + projectId + ".");
            }
        }
        return "";
    }), jsonResponseTransformer);
}

From source file:dk.dma.msiproxy.web.MessageDetailsServlet.java

/**
 * Main GET method/*w  w  w. j  av  a2  s.c o  m*/
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String providerId = request.getParameter("provider");
    String lang = request.getParameter("lang");
    String messageId = request.getParameter("messageId");
    String activeNow = request.getParameter("activeNow");
    String areaHeadingIds = request.getParameter("areaHeadings");

    List<AbstractProviderService> providerServices = providers.getProviders(providerId);

    if (providerServices.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid 'provider' parameter");
        return;
    }

    // Ensure that the language is valid
    lang = providerServices.get(0).getLanguage(lang);

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(lang);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    // Get the messages in the given language for the requested provider
    MessageFilter filter = new MessageFilter().lang(lang);
    Date now = "true".equals(activeNow) ? new Date() : null;
    Integer id = StringUtils.isNumeric(messageId) ? Integer.valueOf(messageId) : null;
    Set<Integer> areaHeadings = StringUtils.isNotBlank(areaHeadingIds) ? Arrays
            .asList(areaHeadingIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toSet())
            : null;

    List<Message> messages = providerServices.stream().flatMap(p -> p.getCachedMessages(filter).stream())
            // Filter on message id
            .filter(msg -> (id == null || id.equals(msg.getId())))
            // Filter on active messages
            .filter(msg -> (now == null || msg.getValidFrom() == null || msg.getValidFrom().before(now)))
            // Filter on area headings
            .filter(msg -> (areaHeadings == null || areaHeadings.contains(getAreaHeadingId(msg))))
            .collect(Collectors.toList());

    // Register the attributes to be used on the JSP apeg
    request.setAttribute("messages", messages);
    request.setAttribute("baseUri", app.getBaseUri());
    request.setAttribute("lang", lang);
    request.setAttribute("locale", locale);
    request.setAttribute("provider", providerId);

    if (request.getServletPath().endsWith("pdf")) {
        generatePdfFile(request, response);
    } else {
        generateHtmlPage(request, response);
    }
}

From source file:com.netflix.spinnaker.fiat.controllers.AuthorizeController.java

@RequestMapping(value = "/{userId:.+}/applications", method = RequestMethod.GET)
public Set<Application.View> getUserApplications(@PathVariable String userId) {
    return permissionsRepository.get(ControllerSupport.convert(userId)).orElseThrow(NotFoundException::new)
            .getView().getApplications().stream().collect(Collectors.toSet());
}

From source file:org.eclipse.sw360.datahandler.common.SW360Utils.java

public static Set<String> filterBUSet(String organisation, Set<String> strings) {
    if (strings == null || isNullOrEmpty(organisation)) {
        return new HashSet<String>();
    }/* www .  j  a  v a2 s  .c  o m*/
    String bu = getBUFromOrganisation(organisation);
    return strings.stream().filter(string -> bu.equals(string)).collect(Collectors.toSet());
}

From source file:se.uu.it.cs.recsys.service.preference.SameCourseFinder.java

/**
 * For example, course 1DL301 and 1DL300, both are Database Design I, but
 * planned in different periods./*from w w  w .  j a va2 s.  c o  m*/
 *
 * @param courseCodeSet, the course collection that at most only one from it can
 * be selected.
 * @param firstTaughtYear, the first year that the course is taught in the plan years
 * @return non-null collection of the course id
 */
public Set<Integer> getIdCollectionToAvoidMoreThanOneSel(Set<String> courseCodeSet, Integer firstTaughtYear) {

    Set<Integer> totalIdSet = new HashSet<>();

    //        Short firstTaughtYear = null;
    //
    //        for (se.uu.it.cs.recsys.api.type.Course c : courseSet) {
    //            if (firstTaughtYear == null) {
    //                firstTaughtYear = c.getTaughtYear().shortValue();
    //            } else {
    //                if (firstTaughtYear > c.getTaughtYear()) {
    //                    firstTaughtYear = c.getTaughtYear().shortValue();
    //                }
    //            }
    //        }

    //        final short finalFirstTaughtYear = firstTaughtYear;

    courseCodeSet.forEach(code -> {
        Set<Integer> partSet = this.courseRepository.findByCode(code).stream()
                .filter(entity -> entity.getTaughtYear() >= firstTaughtYear)
                .map(entity -> entity.getAutoGenId()).collect(Collectors.toSet());

        if (!partSet.isEmpty()) {
            totalIdSet.addAll(partSet);
        }
    });

    return totalIdSet;
}