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:org.wildfly.swarm.plugin.FractionMetadata.java

public Set<FractionMetadata> getFractionDependencies() {
    return this.dependencies.stream().map(FractionRegistry.INSTANCE::of).filter(Objects::nonNull)
            .collect(Collectors.toSet());
}

From source file:com.pscnlab.train.services.impls.TrainServiceImpl.java

@Override
public ResultsTotalDTO<TrainPageDTO> findPageByTime(String time, Integer offset, Integer size,
        Integer memberUUId) {/*w w w .  ja  v a2 s.  c om*/
    Page<Train> trainPage = trainDao.findPageByTime(time, offset, size);
    List<Train> results = trainPage.getResults();
    if (CollectionUtils.isEmpty(results)) {
        return ResultsTotalDTO.build(Collections.EMPTY_LIST, trainPage.getTotalCount());
    }

    Set<Integer> trainIds = results.stream().map(Train::getUuidTrain).collect(Collectors.toSet());
    Map<Integer, List<TrainPeople>> trainPeopleMap = trainPeopleService
            .findMapByTrainIds(new ArrayList<>(trainIds));
    Map<Integer, MemberPageDTO> memberPageDTOMap = new HashMap<>();
    if (trainPeopleMap.size() > 0) {
        Set<Integer> memberIds = trainPeopleMap.values().stream().flatMap(List::stream)
                .map(TrainPeople::getUuidMember).collect(Collectors.toSet());
        memberPageDTOMap = memberSevice.findMemberWithRoleByIds(memberIds);
    }

    //?
    List<TrainPageDTO> trainPageDTOS = new ArrayList<>();
    for (Train result : results) {
        TrainPageDTO trainPageDTO = new TrainPageDTO();
        trainPageDTO.setTrain(result);
        //????
        Boolean isInTrainMember = Boolean.FALSE;
        List<Member> members = new ArrayList<>();
        List<TrainPeople> trainPeoples = trainPeopleMap.get(result.getUuidTrain());
        if (CollectionUtils.isNotEmpty(trainPeoples)) {
            for (TrainPeople trainPeople : trainPeoples) {
                MemberPageDTO memberPageDTO = memberPageDTOMap.get(trainPeople.getUuidMember());
                if (memberPageDTO != null) {
                    members.add(memberPageDTO.getMember());
                    if (memberPageDTO.getMember().getUuidMember().equals(memberUUId)) {
                        isInTrainMember = Boolean.TRUE;
                    }
                }
            }
        }
        trainPageDTO.setIsInTrainMember(isInTrainMember);
        trainPageDTO.setMembers(members);
        trainPageDTOS.add(trainPageDTO);
    }

    return ResultsTotalDTO.build(trainPageDTOS, trainPage.getTotalCount());
}

From source file:com.blackducksoftware.integration.hub.detect.detector.clang.ClangExtractor.java

public Extraction extract(final ClangLinuxPackageManager pkgMgr, final File givenDir, final int depth,
        final ExtractionId extractionId, final File jsonCompilationDatabaseFile) {
    try {/*from  w w  w .  j  a  va 2  s. co  m*/
        logger.info(String.format("Analyzing %s", jsonCompilationDatabaseFile.getAbsolutePath()));
        final File rootDir = fileFinder.findContainingDir(givenDir, depth);
        final File outputDirectory = directoryManager.getExtractionOutputDirectory(extractionId);
        logger.debug(String.format("extract() called; compileCommandsJsonFilePath: %s",
                jsonCompilationDatabaseFile.getAbsolutePath()));
        final Set<File> unManagedDependencyFiles = ConcurrentHashMap.newKeySet(64);
        final List<CompileCommand> compileCommands = CompileCommandsJsonFile
                .parseJsonCompilationDatabaseFile(gson, jsonCompilationDatabaseFile);
        final List<Dependency> bdioComponents = compileCommands.parallelStream()
                .flatMap(compileCommandToDependencyFilePathsConverter(outputDirectory))
                .collect(Collectors.toSet()).parallelStream().filter(StringUtils::isNotBlank).map(File::new)
                .filter(fileIsNewPredicate())
                .flatMap(dependencyFileToLinuxPackagesConverter(rootDir, unManagedDependencyFiles, pkgMgr))
                .collect(Collectors.toSet()).parallelStream()
                .flatMap(linuxPackageToBdioComponentsConverter(pkgMgr)).collect(Collectors.toList());

        final DetectCodeLocation detectCodeLocation = codeLocationAssembler
                .generateCodeLocation(pkgMgr.getDefaultForge(), rootDir, bdioComponents);
        logSummary(bdioComponents, unManagedDependencyFiles);
        return new Extraction.Builder().success(detectCodeLocation).build();
    } catch (final Exception e) {
        return new Extraction.Builder().exception(e).build();
    }
}

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

/**
 * Find all platforms for a given application name.
 *
 * @return a set of plaforms matching request
 *//*from   ww w  . j a  v  a 2s .c  o m*/
public Set<PlatformSearchResponse> getAllPlatforms(final String name, final String platformName) {
    String url = String.format("/platforms/_search?size=%1$s", SEARCH_SIZE);

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

    ElasticSearchResponse<PlatformSearchResponse> esResponse = elasticSearchClient
            .withResponseReader(elasticSearchVsctPlatformReader).post(url, body);

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

From source file:com.github.horrorho.inflatabledonkey.KeyBagManager.java

Set<String> keyBagUUIDs(Collection<Asset> assets) {
    return assets.stream().map(Asset::encryptionKey).map(key -> key.flatMap(FileKeyAssistant::uuid))
            .filter(Optional::isPresent).map(Optional::get)
            .map(uuid -> Base64.getEncoder().encodeToString(uuid)).collect(Collectors.toSet());
}

From source file:com.ggvaidya.scinames.summary.HigherStabilityView.java

public void init() {
    Project project = projectView.getProject();

    // Setup stage.
    stage.setTitle("Higher taxonomy stability between " + project.getDatasets().size() + " datasets");

    // Setup table.
    controller.getTableEditableProperty().set(false);
    //controller.setTableColumnResizeProperty(TableView.CONSTRAINED_RESIZE_POLICY);
    ObservableList<TableColumn> cols = controller.getTableColumnsProperty();
    cols.clear();/*w  w  w . j  a va 2s. com*/

    // Precalculating.

    // Generate list of all dataset columns to search on
    datasetColumns = project.getDatasets().stream().flatMap(ds -> ds.getColumns().stream())
            .collect(Collectors.toSet());

    // Set up columns.
    cols.add(createTableColumnFromPrecalc(precalc, "HigherTaxon"));

    // One column per dataset
    for (Dataset ds : project.getDatasets()) {
        String dsBaseName = ds.getName();
        String dsName = dsBaseName;

        int index = 1;
        while (datasetNames.containsKey(dsName)) {
            dsName = dsBaseName + "_" + index;
            index += 1;
        }
        datasetNames.put(dsName, ds);
        datasetNamesInOrder.add(dsName);

        cols.add(createTableColumnFromPrecalc(precalc, dsName + "_with_synonymy"));
        cols.add(createTableColumnFromPrecalc(precalc, dsName + "_without_synonymy"));
    }

    // Set table items to an observable list.
    controller.getTableItemsProperty().set(higherTaxaList);

    // Set up callbacks so we modify that observable list whenever the user changes the header text.
    controller.getHeaderTextEditableProperty().set(true);
    controller.getHeaderTextProperty().set("Enter higher taxonomy column name here, or set blank for genus");
    controller.getHeaderTextProperty().addListener(a -> {
        generateHigherTaxonomyList(controller.getHeaderTextProperty().get());
    });

    // Start with "" (which means genus)
    generateHigherTaxonomyList("");
}

From source file:com.thinkbiganalytics.rest.JerseyConfig.java

@PostConstruct
/**/*from   w  ww. j  a va 2 s.  c o  m*/
 * Add ability to scan additional Spring Beans annotated with @Path
 */
private void init() {
    //register any additional beans that are path annotated
    Map<String, Object> map = applicationContext.getBeansWithAnnotation(Path.class);
    String packageNames = "com.thinkbiganalytics";
    if (map != null && !map.isEmpty()) {
        String beanPackageNames = map.values().stream().map(o -> o.getClass().getPackage().getName()).distinct()
                .collect(Collectors.joining(","));
        if (StringUtils.isNotBlank(beanPackageNames)) {
            packageNames += "," + beanPackageNames;
        }
    }
    if (map != null) {
        Set<Class<?>> pathClasses = map.values().stream().map(o -> o.getClass()).collect(Collectors.toSet());
        registerClasses(pathClasses);
    }
    configureSwagger(packageNames);
}

From source file:io.fabric8.vertx.maven.plugin.utils.ServiceCombinerUtil.java

private Map<String, List<Set<String>>> findSPIsFromDependencies(List<JavaArchive> jars) {
    Map<String, List<Set<String>>> map = new HashMap<>();

    ArchivePath spiPath = ArchivePaths.create("META-INF/services");

    Set<JavaArchive> serviceProviderArchives = jars.stream().filter(a -> a.contains(spiPath))
            .collect(Collectors.toSet());

    for (JavaArchive archive : serviceProviderArchives) {
        Node node = archive.get(spiPath);
        Set<Node> children = node.getChildren();
        for (Node child : children) {
            String name = child.getPath().get().substring(spiPath.get().length() + 1);
            try {
                List<String> lines = IOUtils.readLines(child.getAsset().openStream(), "UTF-8");
                List<Set<String>> items = map.get(name);
                if (items == null) {
                    items = new ArrayList<>();
                }/*from   www  .j  a va2s .  co  m*/
                items.add(new LinkedHashSet<>(lines));
                map.put(name, items);
            } catch (IOException e) {
                throw new RuntimeException("Cannot read  " + node.getPath().get(), e);
            }
        }
    }

    return map;
}

From source file:se.uu.it.cs.recsys.service.resource.CourseResource.java

@GET
@Path("/year/{year}/period/start/{period}")
@Produces(MediaType.APPLICATION_JSON)// w  w w .  ja v  a 2  s  . c  o m
@ApiOperation(value = "Find course according to taught year and start period.", response = Course.class, responseContainer = "Set")
public Response getCourseByScheduleInfo(
        @ApiParam(name = "year", required = true) @PathParam("year") Integer taughtYear,
        @ApiParam(name = "period", allowableValues = "1,2,3,4", required = true) @PathParam("period") Integer startPeriod) {
    LOGGER.info("Get course taught in {}, started in period {}", taughtYear, startPeriod);

    if (taughtYear == null || taughtYear < UU_FOUND_YEAR) {

        LOGGER.error("Input year is {}, UU founded in {} ", taughtYear, UU_FOUND_YEAR);

        final String REASON = "UU founded yet in year " + UU_FOUND_YEAR;

        return Response.status(Response.Status.BAD_REQUEST).header("Reason", REASON).build();
    }

    if (startPeriod == null) {
        final String REASON = "Start period is null";

        LOGGER.error(REASON);

        return Response.status(Response.Status.BAD_REQUEST).header("Reason", REASON).build();
    }

    Set<Course> courses = this.courseRepository
            .findByTaughtYearAndStartPeriod(taughtYear.shortValue(), startPeriod.shortValue()).stream()
            .map(dbEntity -> CourseConverter.convert(dbEntity)).collect(Collectors.toSet());

    return Response.ok(courses, MediaType.APPLICATION_JSON).build();

}

From source file:com.devicehive.handler.command.CommandSubscribeIntegrationTest.java

@Test
public void shouldSubscribeToDeviceCommands() throws Exception {
    String device1 = randomUUID().toString();
    String device2 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();
    String subscriber3 = randomUUID().toString();

    CommandSubscribeRequest sr1 = new CommandSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);/*w w w . j  a v a2 s.  c  o m*/

    CommandSubscribeRequest sr2 = new CommandSubscribeRequest(subscriber1, device2,
            Collections.singleton("increase_temperature"), null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    CommandSubscribeRequest sr3 = new CommandSubscribeRequest(subscriber2, device2, null, null);
    Request r3 = Request.newBuilder().withBody(sr3).withSingleReply(false).build();
    TestCallback c3 = new TestCallback();
    client.call(r3, c3);

    CommandSubscribeRequest sr4 = new CommandSubscribeRequest(subscriber2, device1,
            Collections.singleton("toggle_lights"), null);
    Request r4 = Request.newBuilder().withBody(sr4).withSingleReply(false).build();
    TestCallback c4 = new TestCallback();
    client.call(r4, c4);

    CommandSubscribeRequest sr5 = new CommandSubscribeRequest(subscriber3, randomUUID().toString(), null, null);
    Request r5 = Request.newBuilder().withBody(sr5).withSingleReply(false).build();
    TestCallback c5 = new TestCallback();
    client.call(r5, c5);

    //wait for subscribers to subscribe
    Stream.of(c1.subscribeFuture, c2.subscribeFuture, c3.subscribeFuture, c4.subscribeFuture,
            c5.subscribeFuture).forEach(CompletableFuture::join);

    //devices send commands
    List<CompletableFuture<Response>> futures = Stream.of(device1, device2).flatMap(device -> {
        List<CompletableFuture<Response>> list = Stream.of("increase_temperature", "toggle_lights")
                .map(name -> {
                    DeviceCommand command = new DeviceCommand();
                    command.setId(0);
                    command.setCommand(name);
                    command.setDeviceGuid(device);
                    CommandInsertRequest event = new CommandInsertRequest(command);
                    CompletableFuture<Response> f = new CompletableFuture<>();
                    client.call(Request.newBuilder().withBody(event).build(), f::complete);
                    return f;
                }).collect(Collectors.toList());
        return list.stream();
    }).collect(Collectors.toList());

    //wait for commands to be delivered
    futures.forEach(CompletableFuture::join);

    assertThat(c1.commands, hasSize(2));
    c1.commands.forEach(event -> {
        assertNotNull(event.getCommand());
        assertEquals(event.getCommand().getDeviceGuid(), device1);
        assertEquals(event.getCommand().getId(), Long.valueOf(0));
    });
    Set<String> names = c1.commands.stream().map(n -> n.getCommand().getCommand()).collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("increase_temperature", "toggle_lights"));

    assertThat(c2.commands, hasSize(1));
    CommandEvent e = c2.commands.stream().findFirst().get();
    assertNotNull(e.getCommand());
    assertEquals(e.getCommand().getDeviceGuid(), device2);
    assertEquals(e.getCommand().getId(), Long.valueOf(0));
    assertEquals(e.getCommand().getCommand(), "increase_temperature");

    assertThat(c3.commands, hasSize(2));
    c3.commands.forEach(event -> {
        assertNotNull(event.getCommand());
        assertEquals(event.getCommand().getDeviceGuid(), device2);
        assertEquals(event.getCommand().getId(), Long.valueOf(0));
    });
    names = c3.commands.stream().map(n -> n.getCommand().getCommand()).collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("increase_temperature", "toggle_lights"));

    assertThat(c4.commands, hasSize(1));
    e = c4.commands.stream().findFirst().get();
    assertNotNull(e.getCommand());
    assertEquals(e.getCommand().getDeviceGuid(), device1);
    assertEquals(e.getCommand().getId(), Long.valueOf(0));
    assertEquals(e.getCommand().getCommand(), "toggle_lights");

    assertThat(c5.commands, is(empty()));
}