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.tesshu.subsonic.client.sample4_music_andmovie.StreamPlayMovieApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    SearchResult2 result2 = search2.get("CORPSE BRIDE", // query, required = true
            0, // artistCount, required = false
            null, // artistOffset, required = false
            0, // albumCount, required = false
            null, // albumOffset, required = false
            10, // songCount, required = false
            null, // songOffset, required = false
            null // musicFolderId, required = false
    );/*from   w ww . j  a va  2  s .c om*/

    Child movie = result2.getSongs().stream().filter(child -> MediaType.VIDEO == child.getType())
            .filter(child -> format.equals(child.getSuffix())).collect(Collectors.toSet()).iterator().next();

    LOG.info(ToStringBuilder.reflectionToString(movie, ToStringStyle.MULTI_LINE_STYLE));

    // not valid?(Perhaps, I have not done convert setting on the server side)
    @SuppressWarnings("unused")
    String size = Integer.toString(movie.getOriginalWidth()) + "x"
            + Integer.toString(movie.getOriginalHeight());

    final IRequestUriObserver uriCallBack = (subject, uri) -> {
        uriStr = uri.toString();
    };

    streamController.stream(

            movie, // id
            null, // maxBitRate
            format, // format
            null, // timeOffset
            null, // size
            true, // estimateContentLength
            false, // converted
            null, // streamCallback
            uriCallBack, callback);

    Group root = new Group();
    Scene scene = new Scene(root, movie.getOriginalWidth(), movie.getOriginalHeight());
    Media media = new Media(uriStr);
    media.errorProperty().addListener((observable, old, cur) -> {
        LOG.info(cur + " : " + uriStr);
    });

    MediaPlayer player = new MediaPlayer(media);
    player.statusProperty().addListener((observable, old, cur) -> {
        LOG.info(cur + " : " + uriStr);
    });

    MediaView view = new MediaView(player);
    ((Group) scene.getRoot()).getChildren().add(view);
    stage.setScene(scene);
    stage.show();
    player.play();

}

From source file:com.fizzed.blaze.internal.DependencyHelper.java

static public Set<String> toGroupArtifactSet(List<Dependency> dependencies) {
    return dependencies.stream().map((d) -> d.getGroupId() + ":" + d.getArtifactId())
            .collect(Collectors.toSet());
}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowPostContingencyViolationsTool.java

@Override
public void run(CommandLine line) throws Exception {
    OnlineConfig config = OnlineConfig.load();
    String workflowId = line.getOptionValue("workflow");
    final LimitViolationFilter violationsFilter = (line.hasOption("type"))
            ? new LimitViolationFilter(Arrays.stream(line.getOptionValue("type").split(","))
                    .map(LimitViolationType::valueOf).collect(Collectors.toSet()), 0)
            : null;//from   w w w.  j  a v a2  s .co  m
    TableFormatterConfig tableFormatterConfig = TableFormatterConfig.load();
    Column[] tableColumns = { new Column("State"), new Column("Contingency"), new Column("Equipment"),
            new Column("Type"), new Column("Value"), new Column("Limit"), new Column("Limit reduction"),
            new Column("Voltage Level") };
    Path cvsOutFile = (line.hasOption("csv")) ? Paths.get(line.getOptionValue("csv")) : null;
    try (OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create()) {
        if (line.hasOption("state") && line.hasOption("contingency")) {
            Integer stateId = Integer.parseInt(line.getOptionValue("state"));
            String contingencyId = line.getOptionValue("contingency");
            List<LimitViolation> violations = onlinedb.getPostContingencyViolations(workflowId, stateId,
                    contingencyId);
            if (violations != null && !violations.isEmpty()) {
                try (TableFormatter formatter = PrintOnlineWorkflowUtils.createFormatter(tableFormatterConfig,
                        cvsOutFile, TABLE_TITLE, tableColumns)) {
                    printStateContingencyViolations(formatter, stateId, contingencyId, violations,
                            violationsFilter);
                }
            } else {
                System.out.println("\nNo post contingency violations for workflow " + workflowId
                        + ", contingency " + contingencyId + " and state " + stateId);
            }
        } else if (line.hasOption("state")) {
            Integer stateId = Integer.parseInt(line.getOptionValue("state"));
            Map<String, List<LimitViolation>> stateViolationsByStateId = onlinedb
                    .getPostContingencyViolations(workflowId, stateId);
            if (stateViolationsByStateId != null && !stateViolationsByStateId.keySet().isEmpty()) {
                try (TableFormatter formatter = PrintOnlineWorkflowUtils.createFormatter(tableFormatterConfig,
                        cvsOutFile, TABLE_TITLE, tableColumns)) {
                    new TreeMap<>(stateViolationsByStateId)
                            .forEach((contingencyId, violations) -> printStateContingencyViolations(formatter,
                                    stateId, contingencyId, violations, violationsFilter));
                }
            } else {
                System.out.println("\nNo post contingency violations for workflow " + workflowId + " and state "
                        + stateId);
            }
        } else {
            if (line.hasOption("contingency")) {
                String contingencyId = line.getOptionValue("contingency");
                Map<Integer, List<LimitViolation>> contingencyViolationsByContingencyId = onlinedb
                        .getPostContingencyViolations(workflowId, contingencyId);
                if (contingencyViolationsByContingencyId != null
                        && !contingencyViolationsByContingencyId.keySet().isEmpty()) {
                    try (TableFormatter formatter = PrintOnlineWorkflowUtils
                            .createFormatter(tableFormatterConfig, cvsOutFile, TABLE_TITLE, tableColumns)) {
                        new TreeMap<>(contingencyViolationsByContingencyId)
                                .forEach((stateId, violations) -> printStateContingencyViolations(formatter,
                                        stateId, contingencyId, violations, violationsFilter));
                    }
                } else {
                    System.out.println("\nNo post contingency violations for workflow " + workflowId
                            + " and contingency " + contingencyId);
                }
            } else {
                Map<Integer, Map<String, List<LimitViolation>>> wfViolations = onlinedb
                        .getPostContingencyViolations(workflowId);
                if (wfViolations != null && !wfViolations.keySet().isEmpty()) {
                    try (TableFormatter formatter = PrintOnlineWorkflowUtils
                            .createFormatter(tableFormatterConfig, cvsOutFile, TABLE_TITLE, tableColumns)) {
                        new TreeMap<>(wfViolations).forEach((stateId, stateViolations) -> {
                            if (stateViolations != null) {
                                new TreeMap<>(stateViolations).forEach((contingencyId, violations) -> {
                                    printStateContingencyViolations(formatter, stateId, contingencyId,
                                            violations, violationsFilter);
                                });
                            }
                        });

                    }
                } else {
                    System.out.println("\nNo post contingency violations for workflow " + workflowId);
                }
            }
        }
    }
}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowSimulationResultsTool.java

@Override
public void run(CommandLine line) throws Exception {
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    String workflowId = line.getOptionValue("workflow");
    OnlineWorkflowResults wfResults = onlinedb.getResults(workflowId);
    if (wfResults != null) {
        if (!wfResults.getUnsafeContingencies().isEmpty()) {
            OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId);
            SecurityIndexType[] securityIndexTypes = null;
            if (line.hasOption(SECURITY_INDEXES)) {
                Set<SecurityIndexType> securityIndexesTypeSet = Arrays
                        .stream(line.getOptionValue(SECURITY_INDEXES).split(","))
                        .map(SecurityIndexType::valueOf).collect(Collectors.toSet());
                securityIndexTypes = securityIndexesTypeSet
                        .toArray(new SecurityIndexType[securityIndexesTypeSet.size()]);
            } else {
                securityIndexTypes = parameters.getSecurityIndexes() == null ? SecurityIndexType.values()
                        : parameters.getSecurityIndexes()
                                .toArray(new SecurityIndexType[parameters.getSecurityIndexes().size()]);
            }//from w w w.ja  v  a2 s .  c  om
            Table table = new Table(securityIndexTypes.length + 2, BorderStyle.CLASSIC_WIDE);
            StringWriter content = new StringWriter();
            CsvWriter cvsWriter = new CsvWriter(content, ',');
            String[] headers = new String[securityIndexTypes.length + 2];
            int i = 0;
            table.addCell("Contingency", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Contingency";
            table.addCell("State", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "State";
            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                table.addCell(securityIndexType.getLabel(), new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = securityIndexType.getLabel();
            }
            cvsWriter.writeRecord(headers);
            for (String contingencyId : wfResults.getUnsafeContingencies()) {
                for (Integer stateId : wfResults.getUnstableStates(contingencyId)) {
                    String[] values = new String[securityIndexTypes.length + 2];
                    i = 0;
                    table.addCell(contingencyId);
                    values[i++] = contingencyId;
                    table.addCell(stateId.toString(), new CellStyle(CellStyle.HorizontalAlign.right));
                    values[i++] = stateId.toString();
                    HashMap<String, String> indexesValues = getIndexesValues(
                            wfResults.getIndexesData(contingencyId, stateId), securityIndexTypes);
                    for (SecurityIndexType securityIndexType : securityIndexTypes) {
                        table.addCell(indexesValues.get(securityIndexType.getLabel()),
                                new CellStyle(CellStyle.HorizontalAlign.center));
                        values[i++] = indexesValues.get(securityIndexType.getLabel());
                    }
                    cvsWriter.writeRecord(values);
                }
            }
            cvsWriter.flush();
            if (line.hasOption("csv"))
                System.out.println(content.toString());
            else
                System.out.println(table.render());
            cvsWriter.close();
        } else
            System.out.println("\nNo contingencies requiring T-D simulation");
    } else
        System.out.println("No results for this workflow");
    onlinedb.close();
}

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

@Path(value = "/levels")
@GET/*from ww w .ja  v a 2s .com*/
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get supported course Levels.", response = CourseLevel.class, responseContainer = "Set")
public Set<CourseLevel> getSupportedCourseLevel() {

    return this.supportedCourseLevelRepository.findAll().stream()
            .map(entity -> CourseLevel.ofDBString(entity.getLevel())).collect(Collectors.toSet());

}

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

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

From source file:delfos.dataset.basic.loader.types.DatasetLoaderAbstract.java

@Override
public UsersDataset getUsersDataset() throws CannotLoadUsersDataset {

    RatingsDataset<RatingType> ratingsDataset = getRatingsDataset();

    return new UsersDatasetAdapter(
            ratingsDataset.allUsers().stream().map(idUser -> new User(idUser)).collect(Collectors.toSet()));

}

From source file:edu.pitt.dbmi.ccd.anno.annotation.AnnotationResourceAssembler.java

/**
 * Convert Annotation to AnnotationResource
 *
 * @param annotation entity//ww  w .ja  va2 s . c o  m
 * @return resource
 */
@Override
public AnnotationResource toResource(Annotation annotation) throws IllegalArgumentException {
    Assert.notNull(annotation);
    AnnotationResource resource = createResourceWithId(annotation.getId(), annotation);
    Set<AnnotationDataResource> data = annotation.getData().stream().filter(d -> d.getParent() == null)
            .map(dataAssembler::toResource).collect(Collectors.toSet());
    resource.addData(data);
    if (annotation.getChildren().size() > 0) {
        resource.add(annotationLinks.children(annotation));
    }
    resource.add(annotationTargetLinks.target(annotation.getTarget()));
    if (annotation.getUser().getAccountId() != null) {
        resource.add(userLinks.user(annotation.getUser()));
    }
    if (annotation.getGroup() != null) {
        resource.add(groupLinks.group(annotation.getGroup()));
    }
    resource.add(vocabularyLinks.vocabulary(annotation.getVocabulary()));
    if (annotation.getParent() != null) {
        resource.add(annotationLinks.parent(annotation));
    }
    resource.setVocabularyResource(vocabularyResourceAssembler.toResource(annotation.getVocabulary()));
    return resource;
}

From source file:com.thoughtworks.go.server.service.AdminsConfigService.java

private String deDuplicatedErrors(List<ConfigErrors> allErrors) {
    Set<String> errors = allErrors.stream().map(ConfigErrors::firstError).collect(Collectors.toSet());
    return StringUtils.join(errors, ",");
}

From source file:se.uu.it.cs.recsys.semantic.ComputingDomainReasonerTest.java

/**
 * Test of getRelatedDomainIds method, of class ComputingDomainReasoner.
 *///from  w w w. j a v a  2 s.  c o m
@Test
public void testGetRelatedDomainIds() throws Exception {

    final String recommenderSystemId = "10003350";

    final Set<String> expNonEmpty = Stream.of("10003269").collect(Collectors.toSet());

    Set<String> result = this.reasoner.getRelatedDomainIds(recommenderSystemId);
    assertEquals(expNonEmpty, result);
}