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

The following examples show how to use java.util.stream.Stream#builder() . 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: AccountTrieNodeDataRequest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
protected Stream<NodeDataRequest> getRequestsFromTrieNodeValue(final Bytes value) {
  final Stream.Builder<NodeDataRequest> builder = Stream.builder();
  final StateTrieAccountValue accountValue = StateTrieAccountValue.readFrom(RLP.input(value));
  // Add code, if appropriate
  if (!accountValue.getCodeHash().equals(Hash.EMPTY)) {
    builder.add(createCodeRequest(accountValue.getCodeHash()));
  }
  // Add storage, if appropriate
  if (!accountValue.getStorageRoot().equals(MerklePatriciaTrie.EMPTY_TRIE_NODE_HASH)) {
    // If storage is non-empty queue download
    final NodeDataRequest storageNode = createStorageDataRequest(accountValue.getStorageRoot());
    builder.add(storageNode);
  }
  return builder.build();
}
 
Example 2
Source File: AnyChildWithRestMatcher.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Stream<PlannerBindings> matches(@Nonnull List<? extends Bindable> children) {
    Stream.Builder<Stream<PlannerBindings>> streams = Stream.builder();
    for (int i = 0; i < children.size(); i++) {
        Bindable child = children.get(i);
        List<Bindable> otherChildren = new ArrayList<>(children.size() - 1);
        otherChildren.addAll(children.subList(0, i));
        otherChildren.addAll(children.subList(i + 1, children.size()));

        Stream<PlannerBindings> childBindings = child.bindTo(selectedChildMatcher);
        // The otherChildrenMatcher is an AllChildrenMatcher wrapping a ReferenceMatcher, so it is guaranteed to
        // produce a single set of PlannerBindings.
        Optional<PlannerBindings> otherBindings = otherChildrenMatcher.matches(otherChildren).findFirst();
        if (!otherBindings.isPresent()) {
            throw new RecordCoreException("invariant violated: couldn't match reference matcher to one of the other children");
        }
        streams.add(childBindings.map(selectedBindings -> selectedBindings.mergedWith(otherBindings.get())));
    }
    return streams.build().flatMap(Function.identity());
}
 
Example 3
Source File: GroupExpressionRef.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Stream<PlannerBindings> bindWithin(@Nonnull ExpressionMatcher<? extends Bindable> matcher) {
    Stream.Builder<Stream<PlannerBindings>> memberStreams = Stream.builder();
    for (T member : members) {
        memberStreams.add(member.bindTo(matcher));
    }
    return memberStreams.build().flatMap(Function.identity()); // concat
}
 
Example 4
Source File: EmployeeTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenBuildStreamFromElements_ObtainStream() {
    Stream.Builder<Employee> empStreamBuilder = Stream.builder();
    
    empStreamBuilder.accept(arrayOfEmps[0]);
    empStreamBuilder.accept(arrayOfEmps[1]);
    empStreamBuilder.accept(arrayOfEmps[2]);

    Stream<Employee> empStream = empStreamBuilder.build();
    
    assert(empStream instanceof Stream<?>);
}
 
Example 5
Source File: StreamBuilderTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testAfterBuilding(int size) {
    Stream.Builder<Integer> sb = Stream.builder();
    IntStream.range(0, size).boxed().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example 6
Source File: Pager.java    From gitlab4j-api with MIT License 5 votes vote down vote up
/**
 * Builds and returns a Stream instance which is pre-populated with all items from all pages.
 *
 * @return a Stream instance which is pre-populated with all items from all pages
 * @throws IllegalStateException if Stream has already been issued
 * @throws GitLabApiException if any other error occurs
 */
public Stream<T> stream() throws GitLabApiException, IllegalStateException {

    if (pagerStream == null) {
        synchronized (this) {
            if (pagerStream == null) {

                // Make sure that current page is 0, this will ensure the whole list is streamed
                // regardless of what page the instance is currently on.
                currentPage = 0;

                // Create a Stream.Builder to contain all the items. This is more efficient than
                // getting a List with all() and streaming that List
                Stream.Builder<T> streamBuilder = Stream.builder();

                // Iterate through the pages and append each page of items to the stream builder
                while (hasNext()) {
                    next().forEach(streamBuilder);
                }

                pagerStream = streamBuilder.build();
                return (pagerStream);
            }
        }
    }

    throw new IllegalStateException("Stream already issued");
}
 
Example 7
Source File: JavaScriptBootstrapUI.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<Component> getChildren() {
    // server-side routing
    if (wrapperElement == null) {
        return super.getChildren();
    }

    // client-side routing,
    // since virtual child is used, it is necessary to change the original
    // UI element to the wrapperElement
    Builder<Component> childComponents = Stream.builder();
    wrapperElement.getChildren().forEach(childElement -> ComponentUtil
            .findComponents(childElement, childComponents::add));
    return childComponents.build();
}
 
Example 8
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Stream<MetricDatum> functionTimerData(FunctionTimer timer) {
    // we can't know anything about max and percentiles originating from a function timer
    double sum = timer.totalTime(getBaseTimeUnit());
    if (!Double.isFinite(sum)) {
        return Stream.empty();
    }
    Stream.Builder<MetricDatum> metrics = Stream.builder();
    double count = timer.count();
    metrics.add(metricDatum(timer.getId(), "count", StandardUnit.COUNT, count));
    metrics.add(metricDatum(timer.getId(), "sum", sum));
    if (count > 0) {
        metrics.add(metricDatum(timer.getId(), "avg", timer.mean(getBaseTimeUnit())));
    }
    return metrics.build();
}
 
Example 9
Source File: StreamBuilderTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testAfterBuilding(int size) {
    Stream.Builder<Integer> sb = Stream.builder();
    IntStream.range(0, size).boxed().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example 10
Source File: StreamBuilderTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testAfterBuilding(int size) {
    Stream.Builder<Integer> sb = Stream.builder();
    IntStream.range(0, size).boxed().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example 11
Source File: AndroidInstrumentationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<BuildTarget> getRuntimeDeps(BuildRuleResolver buildRuleResolver) {
  Stream.Builder<BuildTarget> builder = Stream.builder();
  builder.add(apk.getBuildTarget());
  getApkUnderTest(apk).map(HasInstallableApk::getBuildTarget).ifPresent(builder::add);
  return builder.build();
}
 
Example 12
Source File: StreamBuilderTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testAfterBuilding(int size) {
    Stream.Builder<Integer> sb = Stream.builder();
    IntStream.range(0, size).boxed().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example 13
Source File: TypeInfo.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
/** <code>this</code> and all enclosing types, i.e. the types this type is nested in. */
public Stream<TypeInfo> enclosingTypes() {
    // requires JDK 9: return Stream.iterate(this, TypeInfo::hasEnclosingType, TypeInfo::enclosingType);
    Builder<TypeInfo> builder = Stream.builder();
    for (Class<?> enclosing = getRawType(); enclosing != null; enclosing = enclosing.getEnclosingClass())
        builder.accept(TypeInfo.of(enclosing));
    return builder.build();
}
 
Example 14
Source File: GroupingSpliterator.java    From streams-utils with Apache License 2.0 5 votes vote down vote up
@Override
public boolean tryAdvance(Consumer<? super Stream<E>> action) {
    if (lastBuilderHasBeenConsumed) {
        return false;
    }
    boolean moreElements = true;
    if (firstGroup) {
        moreElements = spliterator.tryAdvance(builder::add);
        firstGroup = false;
    }
    if (!moreElements) {
        action.accept(builder.build());
        lastBuilderHasBeenConsumed = true;
        return true;
    }
    for (int i = 1; i < grouping && moreElements; i++) {
        if (!spliterator.tryAdvance(builder::add)) {
            moreElements = false;
        }
    }
    Stream<E> subStream = builder.build();
    action.accept(subStream);
    if (moreElements) {
        builder = Stream.builder();
        moreElements = spliterator.tryAdvance(builder::add);
    }

    if (!moreElements) {
        lastBuilderHasBeenConsumed = true;
    }

    return true;
}
 
Example 15
Source File: TraversingSpliterator.java    From streams-utils with Apache License 2.0 5 votes vote down vote up
@Override
public boolean tryAdvance(Consumer<? super Stream<E>> action) {
    Stream.Builder<E> builder = Stream.builder();
    boolean hasMore = true;
    for (Spliterator<E> spliterator : spliterators) {
        hasMore &= spliterator.tryAdvance(builder::add);
    }
    if (hasMore) {
        action.accept(builder.build());
        firstGroup.getAndSet(false);
    }
    if (!hasMore && firstGroup.getAndSet(false))
        action.accept(Stream.<E>empty());
    return hasMore;
}
 
Example 16
Source File: AnnotatedJavaTestWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given text describes a set of variable bindings, returns a description of the bindings.
 * Otherwise, returns <CODE>Optional.empty()</CODE>.
 */
protected Optional<String> getBindingsDescriptor( String text)
  {
  Stream.Builder<String> bindings = Stream.builder();
  Matcher varBindingMatcher = varBindingPattern_.matcher( text);
  while( varBindingMatcher.find())
    {
    String varId = toIdentifier( removeEnd( varBindingMatcher.group(1), ".Is"));

    String[] value = fromCsv( varBindingMatcher.group(2)).toArray( String[]::new);
    String valueId =
      value.length == 0?
      "Empty" :
      
      value[0] == null?
      "Null" :

      isBlank( value[0])?
      "Blank" :

      toIdentifier(
        toNumberIdentifiers( value[0])
        .replaceAll( " *<= *", "Leq_")
        .replaceAll( " *< *", "Lt_")
        .replaceAll( " *>= *", "Geq_")
        .replaceAll( " *> *", "Gt_"));

    bindings.add( String.format( "%s_Is_%s", varId, valueId));
    }

  String descriptor = bindings.build().collect( joining( "_"));
  
  return
    descriptor.isEmpty()
    ? Optional.empty()
    : Optional.of( descriptor);
  }
 
Example 17
Source File: XlsUtilities.java    From waltz with Apache License 2.0 5 votes vote down vote up
public static Stream<Row> streamRows(Workbook workbook, SheetNumProvider sheetDefinition) {
    Stream.Builder<Row> streamBuilder = Stream.builder();
    workbook.getSheetAt(sheetDefinition.sheetNum())
            .rowIterator()
            .forEachRemaining(r -> streamBuilder.add(r));
    return streamBuilder.build();
}
 
Example 18
Source File: ThreadMXBeanMetricFamilyCollector.java    From cassandra-exporter with Apache License 2.0 4 votes vote down vote up
@Override
public Stream<MetricFamily> collect() {
    final Stream.Builder<MetricFamily> metricFamilies = Stream.builder();

    {
        final int threadCount = threadMXBean.getThreadCount();
        final int daemonThreadCount = threadMXBean.getDaemonThreadCount();
        final int userThreadCount = threadCount - daemonThreadCount;

        metricFamilies.add(new GaugeMetricFamily("cassandra_jvm_thread_count", "Current number of live threads.", Stream.of(
                new NumericMetric(USER_THREAD_COUNT_LABELS, userThreadCount),
                new NumericMetric(DAEMON_THREAD_COUNT_LABELS, daemonThreadCount)
        )));
    }

    metricFamilies.add(new GaugeMetricFamily("cassandra_jvm_threads_started_total", "Cumulative number of started threads (since JVM start).", Stream.of(new NumericMetric(null, threadMXBean.getTotalStartedThreadCount()))));

    if (perThreadTimingEnabled && threadMXBean instanceof com.sun.management.ThreadMXBean && threadMXBean.isThreadCpuTimeEnabled()) {
        final com.sun.management.ThreadMXBean threadMXBeanEx = (com.sun.management.ThreadMXBean) threadMXBean;

        final long[] threadIds = threadMXBeanEx.getAllThreadIds();
        final ThreadInfo[] threadInfos = threadMXBeanEx.getThreadInfo(threadIds);
        final long[] threadCpuTimes = threadMXBeanEx.getThreadCpuTime(threadIds);
        final long[] threadUserTimes = threadMXBeanEx.getThreadUserTime(threadIds);

        final Stream.Builder<NumericMetric> threadCpuTimeMetrics = Stream.builder();

        for (int i = 0; i < threadIds.length; i++) {
            final long threadCpuTime = threadCpuTimes[i];
            final long threadUserTime = threadUserTimes[i];

            if (threadCpuTime == -1 || threadUserTime == -1) {
                continue;
            }

            final long threadSystemTime = threadCpuTime - threadUserTime;

            final Labels systemModeLabels = new Labels(ImmutableMap.of(
                    "id", String.valueOf(threadIds[i]),
                    "name", threadInfos[i].getThreadName(),
                    "mode", "system"
            ));

            final Labels userModeLabels = new Labels(ImmutableMap.of(
                    "id", String.valueOf(threadIds[i]),
                    "name", threadInfos[i].getThreadName(),
                    "mode", "user"
                    ));

            threadCpuTimeMetrics.add(new NumericMetric(systemModeLabels, nanosecondsToSeconds(threadSystemTime)));
            threadCpuTimeMetrics.add(new NumericMetric(userModeLabels, nanosecondsToSeconds(threadUserTime)));
        }

        metricFamilies.add(new CounterMetricFamily("cassandra_jvm_thread_cpu_time_seconds_total", "Cumulative thread CPU time (since JVM start).", threadCpuTimeMetrics.build()));
    }

    return metricFamilies.build();
}
 
Example 19
Source File: CollectionUtils.java    From tcases with MIT License 4 votes vote down vote up
/**
 * Returns the list of values specified by the given comma-separated string.
 * @see #toCsv
 */
public static Stream<String> fromCsv( String csv)
  {
  Stream.Builder<String> values = Stream.builder();

  if( csv != null)
    {
    int length = csv.length();
    for( int i = 0; i < length; i++)
      {
      if( csv.startsWith( "null", i))
        {
        values.add( null);
        i += "null".length();
        }
      else if( csv.charAt(i) == '\'')
        {
        StringBuilder value = new StringBuilder();
        for( i++; i < length && csv.charAt(i) != '\''; i++)
          {
          if( csv.charAt( i) == '\\')
            {
            i++;
            }

          if( i < length)
            {
            value.append( csv.charAt( i));
            }
          }

        values.add( value.toString());
        i++;
      }
      else
        {
        throw new IllegalArgumentException( String.format( "Invalid CSV: value at index=%s is neither null nor a quoted string", i));
        }
      }
    }
  
  return values.build();
  }
 
Example 20
Source File: BoxCount.java    From imagej-ops with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * Creates a {@link Stream} of t * 2^n translations in n-dimensions
 * <p>
 * The elements in the stream are arrays of coordinates [0, 0, .. 0], [-i, 0,
 * .. 0], [0, -i, 0, .. 0], .. [-i, -i, .. -i], [-2i, 0, .. 0] .. [-ti, -ti,
 * .. -ti], where each array has n elements, i = number of pixels translated,
 * and t = number of translations. If the translations were positive, a part
 * of the interval would not get inspected, because it always starts from [0,
 * 0, ... 0].
 * </p>
 * <p>
 * The order of arrays in the stream is not guaranteed.
 * </p>
 *
 * @param numTranslations Number of translations (1 produces
 *          Stream.of(long[]{0, 0, .. 0}))
 * @param amount Number of pixels shifted in translations
 * @param dimension Current translation dimension (start from last)
 * @param translation The accumulated position of the current translation
 *          (start from {0, 0, .. 0})
 * @return A stream of coordinates of the translations
 */
private static Stream<long[]> translationStream(final long numTranslations,
	final long amount, final int dimension, final long[] translation)
{
	final Stream.Builder<long[]> builder = Stream.builder();
	generateTranslations(numTranslations, amount, dimension, translation,
		builder);
	return builder.build();
}