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

The following examples show how to use java.util.stream.Stream#map() . These examples are extracted from open source projects. 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
public static void rotatePorts(List<PortConnection> connections,
                               Direction source,
                               Direction destination) {
	List<Direction> order = Arrays.asList(Direction.EAST, NORTH, Direction.WEST, Direction.SOUTH);
	
	Stream<PortConnection> stream = connections.stream();
	
	int index = order.indexOf(source);
	boolean useWidth = true;
	while(order.get(index++ % order.size()) != destination) {
		boolean temp = useWidth;
		stream = stream.map(port -> rotatePortCCW(port, temp));
		useWidth = !useWidth;
	}
	
	List<PortConnection> newConns = stream.collect(Collectors.toList());
	connections.clear();
	connections.addAll(newConns);
}
 
Example 2
@Override
public final Stream<FileSlice> getLatestFileSlicesBeforeOrOn(String partitionStr, String maxCommitTime,
    boolean includeFileSlicesInPendingCompaction) {
  try {
    readLock.lock();
    String partitionPath = formatPartitionKey(partitionStr);
    ensurePartitionLoadedCorrectly(partitionPath);
    Stream<FileSlice> fileSliceStream = fetchLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime);
    if (includeFileSlicesInPendingCompaction) {
      return fileSliceStream.map(this::filterBaseFileAfterPendingCompaction);
    } else {
      return fileSliceStream.filter(fs -> !isPendingCompactionScheduledForFileId(fs.getFileGroupId()));
    }
  } finally {
    readLock.unlock();
  }
}
 
Example 3
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext)
        throws Exception {
    final Stream<Consumer<? super ClientRequestContext>> timeoutCustomizers = Stream.of(
            ctx -> ctx.setResponseTimeoutAt(Instant.now().minusSeconds(1)),
            ctx -> ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, 1000),
            ctx -> ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 1000),
            RequestContext::timeoutNow
    );
    return timeoutCustomizers.map(Arguments::of);
}
 
Example 4
public Stream<OffsetInfo> read(Stream<String> stringStream) {
  return stringStream.map(
      s -> {
        try {
          return objectReader.readValue(s);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      });
}
 
Example 5
private static Stream<TSV> encode_evaluation_result_(Stream<Collection<CollectHistory.NamedEvaluation>> evaluated, boolean numericOnly) {
    return evaluated
            .map(c -> {
                final DateTime dt = c.stream().findAny().map(CollectHistory.NamedEvaluation::getDatetime).orElseThrow(() -> new IllegalStateException("no expression result"));
                return new TSV(dt, c, numericOnly);
            });
}
 
Example 6
Source Project: biomedicus   File: ViterbiProcessorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void advance(Y emittedValue) {
  Stream<CandidateProbability<S>> candidateProbabilityStream = emissionProbabilityModel
      .getCandidates(emittedValue)
      .stream();
  Stream<Function<Ancestor<S>, Ancestor<S>>> transitionFunctionStream = candidateProbabilityStream
      .map(candidate -> ancestor -> {
        S candidateState = candidate.getCandidate();
        double transitionLogProbability = transitionProbabilityModel
            .getTransitionLogProbability(reducer.apply(ancestor), candidateState);

        double logProbability = transitionLogProbability + candidate.getEmissionLogProbability()
            + ancestor.getLogProbability();
        return ancestor.createDescendant(logProbability, candidateState);
      });
  Stream<Ancestor<S>> potentialAncestorStream = transitionFunctionStream
      .flatMap(f -> ancestors.stream().map(f::apply));
  Stream<Ancestor<S>> filteredAncestorStream = potentialAncestorStream
      .filter(s -> s.getLogProbability() > Double.NEGATIVE_INFINITY);
  Map<R, Ancestor<S>> ancestorByStateMap = filteredAncestorStream
      .collect(Collectors.toMap(reducer, ancestor -> ancestor, Ancestor::moreProbable));
  Collection<Ancestor<S>> candidates = ancestorByStateMap.values();

  if (candidates.size() > 0) {
    ancestors = candidates;
  } else {
    ancestors = ancestors.stream()
        .map(Ancestor::skip)
        .collect(Collectors.toList());
  }
}
 
Example 7
Source Project: java-client-api   File: ValueConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<LocalTime> StringToLocalTime(Stream<? extends String> values) {
  return (values == null) ? null : values.map(ValueConverter::StringToLocalTime);
}
 
Example 8
Source Project: java-client-api   File: NodeConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<JacksonParserHandle> JsonParserToHandle(Stream<? extends JsonParser> values) {
   return (values == null) ? null : values.map(NodeConverter::JsonParserToHandle);
}
 
Example 9
Source Project: java-client-api   File: NodeConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<XMLStreamReaderHandle> XMLStreamReaderToHandle(Stream<? extends XMLStreamReader> values) {
   return (values == null) ? null : values.map(NodeConverter::XMLStreamReaderToHandle);
}
 
Example 10
/**
 * This method turns a string that might contain wildcards into a regex {@link Pattern} with the
 * specified flags.<br>
 * A string can either be treated as normal wildcard string or a regex string.<br>
 * <br>
 * <b>Wildcard String</b><br>
 * All <code>*</code>s will match zero to infinite many characters.<br>
 * All <code>?</code>s will match zero or one character.<br>
 * <br>
 * Additionally the following options may be applied <i>(the string <code>test</code> will be used
 * an an example here)</i>:
 *
 * <ul>
 *   <li><u>freeMatching</u>: The match will not be bound to word borders. So <code>abctestabc
 *       </code> is still a (partial) match (Only <code>test</code> itself will be matched
 *       though).
 *   <li><u>leetSpeak</u>: Expands all letters to also match leet speak: <a
 *       href="https://qntm.org/l33t">https://qntm.org/l33t</a>. So <code>+3$t</code> is still a
 *       match. See {@link RegexUtil#LEET_PATTERNS}. This flags also implied case insensitive
 *       matching for wildcard strings!
 *   <li><u>ignoreSpaces</u>: This allows infinitely many whitespaces between the letters. So
 *       <code>t es       t</code> is still a match.
 *   <li><u>ignoreDuplicateLetters</u>: This allows letters to be duplicated infinitely many
 *       times. So <code>tteeeeeeesttt</code> is still a match.
 * </ul>
 *
 * <b>Regex String</b><br>
 * If a passed string starts with <code>R=</code>, then the rest will be interpreted as an actual
 * regex.<br>
 *
 * @param wildcard The string that is to be parsed.
 * @param flags Regex flags. See: {@link Pattern#compile}
 * @param freeMatching Determines if the match has to be a free standing word.
 * @param leetSpeak Determines if leet speak also matches. Like a 5 for a S.
 * @param ignoreSpaces Determines if spaces may be ignored.
 * @param ignoreDuplicateLetters Determines if letters may be duplicated (infinitely many times)
 *     and the pattern still matches.
 * @return A regex {@link Pattern} that has been compiled from the string and has the flags set
 *     and options applied if it is not a regex string.
 * @throws PatternSyntaxException If the regex syntax is invalid.
 * @see Pattern#compile
 */
public static Pattern parseWildcardToPattern(
    String wildcard,
    int flags,
    boolean freeMatching,
    boolean leetSpeak,
    boolean ignoreSpaces,
    boolean ignoreDuplicateLetters)
    throws PatternSyntaxException {
  if (wildcard.startsWith("R=")) return Pattern.compile(wildcard.substring(2), flags);
  else {
    flags |= Pattern.CASE_INSENSITIVE;

    Stream<String> stream = TOKENIZER.splitAsStream(escapeRegex(wildcard));

    if (ignoreDuplicateLetters) {
      stream =
          stream.map(
              token -> {
                if (token.length() > 1) return token;
                else return token + "+";
              });
    }

    if (leetSpeak) {
      stream =
          stream.map(
              token -> {
                String firstLetter = Character.toString(token.charAt(0)).toUpperCase();

                if (LEET_PATTERNS.containsKey(firstLetter)) {
                  token = LEET_PATTERNS.get(firstLetter).apply(token);
                }

                return token;
              });
    }

    stream = stream.map(WILDCARD_STAR::apply).map(WILDCARD_QUESTIONMARK::apply);

    String delimiter = ignoreSpaces ? "\\s*" : "";
    String start = freeMatching ? "" : "(?<=^|\\s|\\p{Punct})";
    String end = freeMatching ? "" : "(?=\\p{Punct}|\\s|$)";

    return Pattern.compile(stream.collect(Collectors.joining(delimiter, start, end)), flags);
  }
}
 
Example 11
Source Project: java-client-api   File: NodeConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<TextWriteHandle> TextWriter(Stream<? extends TextWriteHandle> handles) {
   return (handles == null) ? null : handles.map(NodeConverter::TextWriter);
}
 
Example 12
public static Stream<PersistentFilter> wrap( final Path path, final Stream<Filter> filter ) {
	return filter.map( f -> new PersistentFilter( path, f ) );
}
 
Example 13
Source Project: java-client-api   File: ValueConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<String> BigDecimalToString(Stream<? extends BigDecimal> values) {
  return (values == null) ? null : values.map(ValueConverter::BigDecimalToString);
}
 
Example 14
Source Project: Bytecoder   File: String.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Adjusts the indentation of each line of this string based on the value of
 * {@code n}, and normalizes line termination characters.
 * <p>
 * This string is conceptually separated into lines using
 * {@link String#lines()}. Each line is then adjusted as described below
 * and then suffixed with a line feed {@code "\n"} (U+000A). The resulting
 * lines are then concatenated and returned.
 * <p>
 * If {@code n > 0} then {@code n} spaces (U+0020) are inserted at the
 * beginning of each line.
 * <p>
 * If {@code n < 0} then up to {@code n}
 * {@linkplain Character#isWhitespace(int) white space characters} are removed
 * from the beginning of each line. If a given line does not contain
 * sufficient white space then all leading
 * {@linkplain Character#isWhitespace(int) white space characters} are removed.
 * Each white space character is treated as a single character. In
 * particular, the tab character {@code "\t"} (U+0009) is considered a
 * single character; it is not expanded.
 * <p>
 * If {@code n == 0} then the line remains unchanged. However, line
 * terminators are still normalized.
 *
 * @param n  number of leading
 *           {@linkplain Character#isWhitespace(int) white space characters}
 *           to add or remove
 *
 * @return string with indentation adjusted and line endings normalized
 *
 * @see String#lines()
 * @see String#isBlank()
 * @see Character#isWhitespace(int)
 *
 * @since 12
 */
public String indent(int n) {
    if (isEmpty()) {
        return "";
    }
    Stream<String> stream = lines();
    if (n > 0) {
        final String spaces = " ".repeat(n);
        stream = stream.map(s -> spaces + s);
    } else if (n == Integer.MIN_VALUE) {
        stream = stream.map(s -> s.stripLeading());
    } else if (n < 0) {
        stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
    }
    return stream.collect(Collectors.joining("\n", "", "\n"));
}
 
Example 15
Source Project: java-client-api   File: ValueConverter.java    License: Apache License 2.0 4 votes vote down vote up
static public Stream<Boolean> StringToBoolean(Stream<? extends String> values) {
  return (values == null) ? null : values.map(ValueConverter::StringToBoolean);
}
 
Example 16
public Stream<String> retrieveChanges(ChangesRetriever changesRetriever,
                                      Integer version) {
  Stream<CursorQuad> quads = changesRetriever.retrieveChanges(version);
  return quads.map(quad -> {
    Optional<String> dataType = quad.getValuetype();
    if (dataType == null || !dataType.isPresent()) {
      if (quad.getChangeType() == ChangeType.ASSERTED) {
        return changesQuadGenerator.onRelation(quad.getSubject(), quad.getPredicate(), quad.getObject(), graph);
      } else if (quad.getChangeType() == ChangeType.RETRACTED) {
        return changesQuadGenerator.delRelation(quad.getSubject(), quad.getPredicate(), quad.getObject(), graph);
      }
    } else {
      Optional<String> language = quad.getLanguage();
      if (language != null && language.isPresent() && dataType.get().equals(RdfConstants.LANGSTRING)) {
        if (quad.getChangeType() == ChangeType.ASSERTED) {
          return changesQuadGenerator.onLanguageTaggedString(
            quad.getSubject(),
            quad.getPredicate(),
            quad.getObject(),
            language.get(),
            graph
          );
        } else if (quad.getChangeType() == ChangeType.RETRACTED) {
          return changesQuadGenerator.delLanguageTaggedString(
            quad.getSubject(),
            quad.getPredicate(),
            quad.getObject(),
            language.get(),
            graph
          );
        }
      } else {
        if (quad.getChangeType() == ChangeType.ASSERTED) {
          return changesQuadGenerator.onValue(
            quad.getSubject(),
            quad.getPredicate(),
            quad.getObject(),
            dataType.get(),
            graph
          );
        } else if (quad.getChangeType() == ChangeType.RETRACTED) {
          return changesQuadGenerator.delValue(
            quad.getSubject(),
            quad.getPredicate(),
            quad.getObject(),
            dataType.get(),
            graph
          );
        }
      }
    }
    return ""; // return empty string for unchanged quads
  });
}
 
Example 17
Source Project: incubator-tuweni   File: AsyncResult.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns a result that completes when all of the given results complete. If any results complete exceptionally, then
 * the resulting completion also completes exceptionally.
 *
 * @param <T> The type of the values that this result will complete with.
 * @param rs The results to combine.
 * @return A new result.
 */
static <T> AsyncResult<List<T>> combine(Stream<? extends AsyncResult<? extends T>> rs) {
  Stream<AsyncResult<List<T>>> ls = rs.map(r -> r.thenApply(Collections::singletonList));
  return ls.reduce(AsyncResult.completed(new ArrayList<>()), (r1, r2) -> r1.thenCombine(r2, (l1, l2) -> {
    l1.addAll(l2);
    return l1;
  }));
}
 
Example 18
/**
 * Implement map.
 *
 * @param <T> Generic type T
 * @param <R> Generic type R
 * @param stream The {@code Stream} to map.
 * @param mapper A mapping {@code Function} to apply.
 * @return The resulting {@code Stream}.
 */
private static <T,R> Stream<R> map_internal(Stream<T> stream,
    Function<? super T,? extends R> mapper) {
    return stream.map(mapper);
}
 
Example 19
/**
 * Cached item neighborhood. Caches a pre-calculated set of neighborhoods.
 *
 * @param items         item index
 * @param neighborhoods pre-calculated neighborhoods
 * @param <I>           item type
 * @return item neighborhood
 */
public static <I> ItemNeighborhood<I> cached(FastItemIndex<I> items, Stream<Tuple2<I, Stream<Tuple2od<I>>>> neighborhoods) {
    return new ItemNeighborhood<>(items, new CachedNeighborhood(items.numItems(), neighborhoods
            .map(t -> tuple(items.item2iidx(t.v1), t.v2.map(items::item2iidx)))));
}
 
Example 20
Source Project: cyclops   File: BaseSimpleReact.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Start a reactive dataflow from a stream.
 *
 * @param stream that will be used to drive the reactive dataflow
 * @return Next stage in the reactive flow
 */
public <U> BaseSimpleReactStream<U> from(final Stream<U> stream) {

    final Stream s = stream.map(it -> CompletableFuture.completedFuture(it));
    return construct(s);
}