Java Code Examples for java.util.stream.Stream#flatMap()

The following examples show how to use java.util.stream.Stream#flatMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Classes.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<? extends Type> apply( Type type )
{
    Class clazz = RAW_CLASS.apply( type );

    if( clazz.isInterface() )
    {
        Stream<? extends Type> genericInterfaces = Arrays.stream( clazz.getGenericInterfaces() );
        Stream<? extends Type> intfaces = genericInterfaces.flatMap( INTERFACES_OF );
        return concat( Stream.of( type ), intfaces );
    }
    else
    {
        if( type.equals( Object.class ) )
        {
            return Arrays.stream( clazz.getGenericInterfaces() );
        }
        else
        {
            return concat( Stream.of( clazz.getGenericInterfaces() ).flatMap( INTERFACES_OF ),
                           Stream.of( clazz.getSuperclass() ).flatMap( INTERFACES_OF ) );

        }
    }
}
 
Example 2
Source File: GenerativeOperationalIT.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates a tree of patterns where such that each child is a generalisation of its parent pattern.
 * @param basePattern starting specific pattern
 * @param ctx schema(type) context
 * @return map containing parent->{children} mappings
 */
private static HashMultimap<Pattern, Pattern> generatePatternTree(Pattern basePattern, TransactionContext ctx, List<Operator> ops, int maxOps){
    HashMultimap<Pattern, Pattern> patternTree = HashMultimap.create();
    Set<Pattern> output = Operators.removeSubstitution().apply(basePattern, ctx).collect(Collectors.toSet());

    int applications = 0;
    while (!(output.isEmpty() || applications > maxOps)){
        Stream<Pattern> pstream = output.stream();
        for(Operator op : ops){
            pstream = pstream.flatMap(parent -> op.apply(parent, ctx).peek(child -> patternTree.put(parent, child)));
        }
        output = pstream.collect(Collectors.toSet());
        applications++;
    }
    return patternTree;
}
 
Example 3
Source File: Board.java    From lizzie with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns all the nodes at the given depth in the history tree, always including a node from the
 * main variation (possibly less deep that the given depth).
 *
 * @return the list of candidate nodes
 */
private List<BoardHistoryNode> branchCandidates(BoardHistoryNode node) {
  int targetDepth = node.getData().moveNumber;
  Stream<BoardHistoryNode> nodes = singletonList(history.root()).stream();
  for (int i = 0; i < targetDepth; i++) {
    nodes = nodes.flatMap(n -> n.getVariations().stream());
  }
  LinkedList<BoardHistoryNode> result = nodes.collect(Collectors.toCollection(LinkedList::new));

  if (result.isEmpty() || !result.get(0).isMainTrunk()) {
    BoardHistoryNode endOfMainTrunk = history.root();
    while (endOfMainTrunk.next().isPresent()) {
      endOfMainTrunk = endOfMainTrunk.next().get();
    }
    result.addFirst(endOfMainTrunk);
    return result;
  } else {
    return result;
  }
}
 
Example 4
Source File: OptionalTest.java    From protonpack with MIT License 5 votes vote down vote up
@Test
public void
stream_of_nonempty_optionals() {
    Stream<Integer> numbers = Stream.of(123, 456);
    Stream<Integer> results = numbers.flatMap(n -> StreamUtils.stream(maybeAdd3(n)));
    List<Integer> resultList = results.collect(Collectors.toList());
    assertEquals(Arrays.asList(126, 459), resultList);
}
 
Example 5
Source File: TransformationWriter.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void writeLocal(String string) throws IOException {
    Stream<HtmlElement> stream = Html.stream(string);
    for (int index = 0; index < steps.length; ++index ) {
        stream = stream.flatMap(steps[index]);
        log.error("adding {}", steps[index]);
    }
    char[] cache = stream.map(HtmlElements.TO_HTML).collect(Collectors.joining()).toCharArray();
    originalWriter.write(cache, 0, cache.length);
}
 
Example 6
Source File: MatchTransformerImpl.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a decorator map from a mapping of GroupMatchers.
 */
private static DecoratorMap group_map_(Map<String, PathMatcher> paths) {
    if (paths.isEmpty()) return concat();

    return new DecoratorMap() {
        @Override
        public Stream<Consumer<MutableContext>> map(Stream<Consumer<MutableContext>> in, Context ctx) {
            final Map<String, TimeSeriesValueSet> pathMapping = paths.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey,
                            pmEntry -> {
                                return ctx.getTSData()
                                .getCurrentCollection()
                                .get(p -> pmEntry.getValue().match(p.getPath()), x -> true);
                            }));

            for (final Map.Entry<String, TimeSeriesValueSet> pm
                         : pathMapping.entrySet()) {
                final String identifier = pm.getKey();
                final List<Consumer<MutableContext>> applications = pm.getValue().stream()
                        .map(group -> {
                            Consumer<MutableContext> application = (nestedCtx) -> nestedCtx.putGroupAliasByName(identifier, group::getGroup);
                            return application;
                        })
                        .collect(Collectors.toList());

                in = in.flatMap(inApplication -> applications.stream().map(inApplication::andThen));
            }
            return in;
        }
    };
}
 
Example 7
Source File: WordCount.java    From unix-stream with MIT License 5 votes vote down vote up
@Override
public Stream<String> apply(Stream<String> input) {
    if (option.equals(Option.L)) {
        return Stream.of(valueOf(input.count()));
    } else {
        Stream<String> stringStream = input.flatMap(s -> Stream.of(s.split(" +")));
        return Stream.of(valueOf(stringStream.count()));
    }
}
 
Example 8
Source File: HttpCallsTestResultPayloadExtractor.java    From webtau with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<TestResultPayload> extract(Stream<TestStep> testSteps) {
    Stream<HttpValidationResult> payloads = testSteps
            .flatMap(s -> s.getCombinedPayloadsOfType(HttpValidationResult.class));

    return Stream.of(new TestResultPayload(HTTP_CALLS_PAYLOAD_NAME,
            payloads.map(HttpValidationResult::toMap).collect(Collectors.toList())));
}
 
Example 9
Source File: Quantifier.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Stream<PlannerBindings> bindTo(@Nonnull final ExpressionMatcher<? extends Bindable> matcher) {
    Stream<PlannerBindings> bindings = matcher.matchWith(this);
    return bindings.flatMap(outerBindings -> matcher.getChildrenMatcher().matches(ImmutableList.of(getRangesOver()))
            .map(outerBindings::mergedWith));
}
 
Example 10
Source File: NotPredicate.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Stream<PlannerBindings> bindTo(@Nonnull ExpressionMatcher<? extends Bindable> matcher) {
    Stream<PlannerBindings> bindings = matcher.matchWith(this);
    return bindings.flatMap(outerBindings -> matcher.getChildrenMatcher().matches(ImmutableList.of(getChild()))
            .map(outerBindings::mergedWith));
}
 
Example 11
Source File: InstanceIdentifier.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a stream of hostname identifiers from a stream of hostname expressions
 *
 * @param hostnameExpressions the hostname expressions
 * @return the hostname identifiers
 */
public static Stream<InstanceIdentifier> createIdentifiers(Stream<String> hostnameExpressions) {
    return hostnameExpressions.flatMap(hostnameExpression -> extractHostnames(hostnameExpression).flatMap(hostname -> {
        ExtractedRange extractedRange = new ExtractedRange(hostname, '(', ')');
        if (extractedRange.range == null) {
            return Stream.of(new InstanceIdentifier(hostname, 1));
        }
        if (!StringUtils.isEmpty(extractedRange.afterClose)) {
            throw new IllegalArgumentException("No characters expected after )");
        }
        return extractedRange.range.map(numString -> new InstanceIdentifier(extractedRange.beforeOpen, Integer.parseInt(numString)));
    }));
}
 
Example 12
Source File: CompositeModel.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public Stream<DependencyModel> dependencies()
{
    Stream<Dependencies> models = Stream.of( this.mixinsModel, compositeMethodsModel );
    return models.flatMap( Dependencies::dependencies );
}
 
Example 13
Source File: QuerySuggestionSource.java    From otroslogviewer with Apache License 2.0 4 votes vote down vote up
protected Set<String> getValuesForFieldFromHistory(String field, List<SuggestionQuery> history) {
  final Stream<String> stringStream = history.stream().map(SuggestionQuery::getValue).filter(x -> x.contains(field));
  final Stream<String> fieldValues = stringStream.flatMap(s -> getFieldValues(field, s).stream());
  return fieldValues.collect(Collectors.toSet());
}
 
Example 14
Source File: Gherkin.java    From gherkin-java with MIT License 4 votes vote down vote up
public Stream<Envelope> messages() {
    Stream<Envelope> envelopeStream = envelopes != null ? envelopes.stream() : envelopeStreamFromPaths(paths);
    return envelopeStream
            .flatMap((Function<Envelope, Stream<Envelope>>) envelope -> parserMessageStream(envelope, includeSource, includeAst, includePickles));
}
 
Example 15
Source File: Gherkin.java    From cucumber with MIT License 4 votes vote down vote up
public Stream<Envelope> messages() {
    Stream<Envelope> envelopeStream = envelopes != null ? envelopes.stream() : envelopeStreamFromPaths(paths);
    return envelopeStream
            .flatMap((Function<Envelope, Stream<Envelope>>) envelope -> parserMessageStream(envelope, includeSource, includeAst, includePickles));
}
 
Example 16
Source File: MiniRaftCluster.java    From ratis with Apache License 2.0 4 votes vote down vote up
private Stream<RaftServerImpl> getServerStream(RaftGroupId groupId) {
  final Stream<RaftServerProxy> stream = getRaftServerProxyStream(groupId);
  return groupId != null?
      stream.filter(s -> s.containsGroup(groupId)).map(s -> RaftServerTestUtil.getRaftServerImpl(s, groupId))
      : stream.flatMap(s -> RaftServerTestUtil.getRaftServerImpls(s).stream());
}
 
Example 17
Source File: UiSpecServiceTest.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private Stream<UiSchema> flattenUiSchema(final Stream<UiSchema> uiSchema) {
    return uiSchema
            .flatMap(u -> u.getItems() == null ? Stream.of(u)
                    : Stream.concat(Stream.of(u), flattenUiSchema(u.getItems().stream())));
}
 
Example 18
Source File: RPEntity.java    From stendhal with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get a stream of all equipped items.
 *
 * @return equipped items
 */
private Stream<Item> equippedStream() {
	Stream<String> slotNames = Slots.CARRYING.getNames().stream();
	Stream<RPSlot> slots = slotNames.map(this::getSlot).filter(Objects::nonNull);
	return slots.flatMap(this::slotStream);
}
 
Example 19
Source File: Classes.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
public static Stream<Type> typesOf( Stream<? extends Type> types )
{
    return types.flatMap( TYPES_OF );
}
 
Example 20
Source File: MiniRaftCluster.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
private Stream<RaftServerImpl> getServerStream(RaftGroupId groupId) {
  final Stream<RaftServerProxy> stream = getRaftServerProxyStream(groupId);
  return groupId != null?
      stream.filter(s -> s.containsGroup(groupId)).map(s -> RaftServerTestUtil.getRaftServerImpl(s, groupId))
      : stream.flatMap(s -> RaftServerTestUtil.getRaftServerImpls(s).stream());
}