Example usage for java.util.stream Stream collect

List of usage examples for java.util.stream Stream collect

Introduction

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

Prototype

<R, A> R collect(Collector<? super T, A, R> collector);

Source Link

Document

Performs a mutable reduction operation on the elements of this stream using a Collector .

Usage

From source file:module.mailtracking.domain.MailTracking.java

public java.util.Set<User> getTotalUsers() {
    final Stream<User> viewers = getViewersGroup().getMembers();
    final Stream<User> operators = getOperatorsGroup().getMembers();
    final Stream<User> managers = getManagersGroup().getMembers();
    final Stream<User> stream = Stream.concat(Stream.concat(viewers, operators), managers);
    return stream.collect(Collectors.toSet());
}

From source file:org.lightjason.examples.pokemon.simulation.agent.pokemon.CLevel.java

/**
 * ctor/*from  ww w  .j av a 2s  .  com*/
 *
 * @param p_pokemon pokemon name
 * @param p_index index number of pokemon
 * @param p_ethnic stream with ethnic types
 * @param p_ethnicvalue stream with ethnic values
 * @param p_motivation stream with motivation types
 * @param p_motivationvalue stream with motivation value
 * @param p_attribute stream with attributes types
 * @param p_attributesvalue stream with attributes values
 * @param p_attack attack
 */
public CLevel(final String p_pokemon, final int p_index, final Stream<String> p_ethnic,
        final Stream<ImmutableTriple<Number, Number, Number>> p_ethnicvalue, final Stream<String> p_motivation,
        final Stream<ImmutableTriple<Number, Number, Number>> p_motivationvalue,
        final Stream<CAttribute> p_attribute,
        final Stream<ImmutableTriple<Number, Number, Number>> p_attributesvalue,
        final Stream<CAttack> p_attack) {
    m_texturepath = MessageFormat.format(ICONFILENAME, p_pokemon.trim().toLowerCase().replaceAll(" ", "_"),
            p_index);
    m_ethnic = CLevel.initialize(p_ethnic, p_ethnicvalue);
    m_attribute = CLevel.initialize(p_attribute, p_attributesvalue);
    m_motivation = CLevel.initialize(p_motivation, p_motivationvalue);
    m_attack = Collections.unmodifiableSet(p_attack.collect(Collectors.toSet()));
}

From source file:org.codice.ddf.configuration.migration.ExportMigrationManagerImpl.java

@VisibleForTesting
ExportMigrationManagerImpl(MigrationReport report, Path exportFile, CipherUtils cipherUtils,
        Stream<? extends Migratable> migratables, ZipOutputStream zos) {
    Validate.notNull(report, "invalid null report");
    Validate.isTrue(report.getOperation() == MigrationOperation.EXPORT, "invalid migration operation");
    Validate.notNull(migratables, "invalid null migratables");
    Validate.notNull(cipherUtils, "invalid null cipher utils");
    this.report = report;
    this.exportFile = exportFile;
    this.cipherUtils = cipherUtils;
    this.zipOutputStream = zos;
    // pre-create contexts for all registered migratables
    this.contexts = migratables.collect(Collectors.toMap(Migratable::getId,
            m -> new ExportMigrationContextImpl(report, m, zipOutputStream, new CipherUtils(exportFile)),
            ConfigurationMigrationManager.throwingMerger(), LinkedHashMap::new)); // to preserved ranking order and remove duplicates
}

From source file:no.asgari.civilization.server.action.GameAction.java

private List<Item> getAllRevealedItems(PBF pbf) {
    //Had to have comparator inside sort, otherwise weird exception
    Stream<Item> discardedStream = pbf.getDiscardedItems().stream()
            .sorted((o1, o2) -> o1.getSheetName().compareTo(o2.getSheetName()));

    Stream<Item> playerStream = pbf.getPlayers().stream().flatMap(p -> p.getItems().stream())
            .filter(it -> !it.isHidden()).sorted((o1, o2) -> o1.getSheetName().compareTo(o2.getSheetName()));

    Stream<Item> concatedStream = Stream.concat(discardedStream, playerStream);
    return concatedStream.collect(toList());
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void reportHasWarningMessage(Stream<MigrationWarning> warnings, Matcher<String> matcher) {
    final List<MigrationWarning> ws = warnings.collect(Collectors.toList());
    final long count = ws.stream().filter((w) -> matcher.matches(w.getMessage())).count();
    final Description d = new StringDescription();

    matcher.describeTo(d);/*from  w ww . j  ava 2s  .c  o  m*/
    assertThat("There are " + count + " matching warning(s) with " + d
            + " in the migration report.\nWarnings are: " + ws.stream().map(MigrationWarning::getMessage)
                    .collect(Collectors.joining("\",\n\t\"", "[\n\t\"", "\"\n]")),
            count, equalTo(1L));
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void reportHasErrorMessage(Stream<MigrationException> errors, Matcher<String> matcher) {
    final List<MigrationException> es = errors.collect(Collectors.toList());
    final long count = es.stream().filter((e) -> matcher.matches(e.getMessage())).count();
    final Description d = new StringDescription();

    matcher.describeTo(d);//from  w w w.j a va2  s.  c  o m

    assertThat("There are " + count + " matching error(s) with " + d + " in the migration report.\nErrors are: "
            + es.stream().map(MigrationException::getMessage)
                    .collect(Collectors.joining("\",\n\t\"", "[\n\t\"", "\"\n]")),
            count, equalTo(1L));
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void reportHasInfoMessage(Stream<MigrationInformation> infos, Matcher<String> matcher) {
    final List<MigrationInformation> is = infos.collect(Collectors.toList());
    final long count = is.stream().filter((w) -> matcher.matches(w.getMessage())).count();
    final Description d = new StringDescription();

    matcher.describeTo(d);//from w  ww .j  a  va2s  .  c  om
    assertThat("There are " + count + " matching info message(s) with " + d
            + " in the migration report.\nWarnings are: " + is.stream().map(MigrationInformation::getMessage)
                    .collect(Collectors.joining("\",\n\t\"", "[\n\t\"", "\"\n]")),
            count, equalTo(1L));
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.io.writer.json.JCasTextSpanAnnotationGraphFactory.java

@Override
public SpanAnnotationGraph<SpanTextLabel> apply(final JCas jCas) {
    final ReverseLookupOrderedSet<SpanTextLabel> spanAnnotationVector;
    final Sparse3DObjectMatrix<String, SpanTextLabel> spanAnnotationMatrix;
    {/* w  w  w  .  j  ava  2 s .  com*/
        final Collection<ArgumentComponent> argumentComponents = JCasUtil.select(jCas, ArgumentComponent.class);

        {
            final int argumentComponentCount = argumentComponents.size();
            LOG.info(String.format("Processing %d argument components.", argumentComponentCount));
            // The list of all annotations, their index in the list serving
            // as
            // their
            // ID
            spanAnnotationVector = new ReverseLookupOrderedSet<>(
                    new ArrayList<SpanTextLabel>(argumentComponentCount));
            // Just use the size "argumentComponentCount" directly here
            // because
            // it
            // is assumed that spans
            // don't overlap
            spanAnnotationMatrix = new Sparse3DObjectMatrix<>(
                    new Int2ObjectOpenHashMap<>(argumentComponentCount + 1),
                    ESTIMATED_SPAN_BEGIN_TO_END_MAP_MAX_CAPACITY, ESTIMATED_ANNOTATION_MAP_MAX_CAPACITY);
        }

        for (final ArgumentComponent argumentComponent : argumentComponents) {
            final SpanTextLabel spanAnnotation = SpanTextAnnotationFactory.getInstance()
                    .apply(argumentComponent);
            final Span span = spanAnnotation.getSpanText().getSpan();
            final int begin = span.getBegin();
            final int end = span.getEnd();
            final String label = spanAnnotation.getLabel();
            final Map<String, SpanTextLabel> spanAnnotations = spanAnnotationMatrix.fetch3DMap(begin, end);
            final SpanTextLabel oldSpanAnnotation = spanAnnotations.put(label, spanAnnotation);
            if (oldSpanAnnotation != null) {
                LOG.warn(String.format("Annotation label \"%s\" already exists for span [%d, %d]; Overwriting.",
                        label, begin, end));
            }
            spanAnnotationVector.add(spanAnnotation);
        }
    }

    final Collection<ArgumentRelation> argumentRelations = JCasUtil.select(jCas, ArgumentRelation.class);
    final Object2IntMap<SpanTextLabel> spanAnnotationIds = spanAnnotationVector.getReverseLookupMap();
    LOG.info(String.format("Processing %d argument relations.", argumentRelations.size()));

    final int initialTableRelationValue = -1;
    final Supplier<int[]> transitionTableArraySupplier = () -> {
        final int[] result = new int[spanAnnotationIds.size()];
        // Pre-fill the array in the case that there is no transition for a
        // given annotation
        Arrays.fill(result, initialTableRelationValue);
        return result;
    };
    final ArgumentTransitionTableCollector argTransitionTableCollector = new ArgumentTransitionTableCollector(
            transitionTableArraySupplier, initialTableRelationValue,
            annot -> getAnnotationId(annot, spanAnnotationMatrix, spanAnnotationIds));

    final Stream<ArgumentRelation> argumentRelationStream = argumentRelations.stream().map(argumentRelation -> {
        final ArgumentUnit source = argumentRelation.getSource();
        final Map<Attribute, Object> sourceAnnotAttrs = getSpanTextLabel(source, spanAnnotationMatrix)
                .getAttributes();
        // If the source annotation doesn't have its own category already set, set it to
        // the type label of the relation between it and its target
        sourceAnnotAttrs.putIfAbsent(Attribute.CATEGORY, argumentRelation.getType().getShortName());
        return argumentRelation;
    });
    final int[] argumentTransitionTable = argumentRelationStream.collect(argTransitionTableCollector);

    return new SpanAnnotationGraph<>(spanAnnotationVector, argumentTransitionTable);
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private MenuItem createAddMenu(String name, TreeView<Object> elements, TreeItem<Object> selected) {
    ListHolder listHolder = (ListHolder) selected.getValue();

    MenuItem add = new MenuItem(name);
    add.setOnAction(event -> {//from w  w  w . j  a v a 2 s. co  m
        Stream<ClassHolder> st = SubclassManager.getInstance().getClassWithAllSubclasses(listHolder.type)
                .stream().map(ClassHolder::new);
        List<ClassHolder> list = st.collect(Collectors.toList());

        Optional<ClassHolder> choice;

        if (list.size() == 1) {
            choice = Optional.of(list.get(0));
        } else {
            ChoiceDialog<ClassHolder> cd = new ChoiceDialog<>(list.get(0), list);
            cd.setTitle("Select class");
            cd.setHeaderText(null);
            choice = cd.showAndWait();
        }
        choice.ifPresent(toCreate -> {
            try {
                IOEntity obj = toCreate.clazz.newInstance();

                listHolder.list.add(obj);
                TreeItem<Object> treeItem = createTreeItem(obj);
                selected.getChildren().add(treeItem);
                elements.getSelectionModel().select(treeItem);
                elements.scrollTo(elements.getSelectionModel().getSelectedIndex());

                editor.getHistory().valueCreated(treeItemToScriptString(selected), toCreate.clazz);
            } catch (ReflectiveOperationException e) {
                log.log(Level.WARNING, String.format("Couldn't instantiate %s", toCreate.clazz.getName()), e);
                Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                        "Couldn't instantiate " + toCreate.clazz);
            }
        });
    });

    return add;
}

From source file:nc.noumea.mairie.appock.services.impl.ImportExcelServiceImpl.java

private PhotoArticleCatalogue recuperePhotoArticleCatalogue(XSSFSheet firstSheet, String nomFichier, int numRow,
        String reference) throws IOException, ImportExcelException {

    Stream<XSSFShape> shapeStream = firstSheet.getDrawingPatriarch().getShapes().stream() //
            .filter(shape -> {// w  w  w  . j a v  a 2 s.  co  m
                if (!(shape instanceof XSSFPicture)) {
                    return false;
                }
                XSSFPicture picture = (XSSFPicture) shape;
                XSSFClientAnchor anchor = (XSSFClientAnchor) picture.getAnchor();
                XSSFRow pictureRow = firstSheet.getRow(anchor.getRow1());
                return (anchor.getCol1() == IMPORT_EXCEL_COLONNE_PHOTO && pictureRow != null
                        && pictureRow.getRowNum() == numRow);
            });

    List<XSSFShape> listeShape = shapeStream.collect(Collectors.toList());
    if (listeShape.isEmpty()) {
        throw new ImportExcelException(numRow + 1, reference, "Aucune image n'a t trouve");
    } else if (listeShape.size() > 1) {
        throw new ImportExcelException(numRow + 1, reference, "Plusieurs images ont t trouves");
    }

    XSSFPicture picture = (XSSFPicture) listeShape.get(0);
    byte[] content = picture.getPictureData().getData();
    content = AppockUtil.scale(content, 80, 80);

    if (content == null) {
        throw new ImportExcelException(numRow + 1, reference, "Aucune image n'a t trouve");
    }

    return catalogueService.savePhotoArticleCatalogue(content, nomFichier);
}