java.util.stream.IntStream类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(170)

本文整理了Java中java.util.stream.IntStream类的一些代码示例,展示了IntStream类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。IntStream类的具体详情如下:
包路径:java.util.stream.IntStream
类名称:IntStream

IntStream介绍

[英]A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.

The following example illustrates an aggregate operation using Stream and IntStream, computing the sum of the weights of the red widgets:

int sum = widgets.stream()

See the class documentation for Stream and the package documentation for java.util.stream for additional specification of streams, stream operations, stream pipelines, and parallelism.
[中]支持顺序和并行聚合操作的原始int值元素序列。这是流的int原语专门化。
以下示例演示了使用Stream和IntStream的聚合操作,计算红色小部件的权重之和:

int sum = widgets.stream()

有关流、流操作、流管道和并行性的其他规范,请参阅流的类文档和java.util.stream的包文档。

代码示例

代码示例来源:origin: prestodb/presto

private String columnDefinitions(List<DataTypeTest.Input<?>> inputs)
  {
    List<String> columnTypeDefinitions = inputs.stream()
        .map(DataTypeTest.Input::getInsertType)
        .collect(toList());
    Stream<String> columnDefinitions = range(0, columnTypeDefinitions.size())
        .mapToObj(i -> format("col_%d %s", i, columnTypeDefinitions.get(i)));
    return Joiner.on(",\n").join(columnDefinitions.iterator());
  }
}

代码示例来源:origin: apache/incubator-dubbo

public static int getConsumerAddressNum(String serviceUniqueName) {
    Set<ConsumerInvokerWrapper> providerInvokerWrapperSet = ProviderConsumerRegTable.getConsumerInvoker(serviceUniqueName);
    return providerInvokerWrapperSet.stream()
        .map(w -> w.getRegistryDirectory().getUrlInvokerMap())
        .filter(Objects::nonNull)
        .mapToInt(Map::size).sum();
  }
}

代码示例来源:origin: prestodb/presto

@Override
protected void print(List<String> warnings)
{
  console.reprintLine("");
  warnings.stream()
      .forEach(console::reprintLine);
  // Remove warnings from previous screen
  range(0, DISPLAYED_WARNINGS - warnings.size())
      .forEach(line -> console.reprintLine(""));
}

代码示例来源:origin: prestodb/presto

public NodePartitionMap(List<Node> partitionToNode, ToIntFunction<Split> splitToBucket)
{
  this.partitionToNode = ImmutableList.copyOf(requireNonNull(partitionToNode, "partitionToNode is null"));
  this.bucketToPartition = IntStream.range(0, partitionToNode.size()).toArray();
  this.splitToBucket = requireNonNull(splitToBucket, "splitToBucket is null");
}

代码示例来源:origin: spring-projects/spring-framework

protected String formatInvokeError(String text, Object[] args) {
  String formattedArgs = IntStream.range(0, args.length)
      .mapToObj(i -> (args[i] != null ?
          "[" + i + "] [type=" + args[i].getClass().getName() + "] [value=" + args[i] + "]" :
          "[" + i + "] [null]"))
      .collect(Collectors.joining(",\n", " ", " "));
  return text + "\n" +
      "Controller [" + getBeanType().getName() + "]\n" +
      "Method [" + getBridgedMethod().toGenericString() + "] " +
      "with argument values:\n" + formattedArgs;
}

代码示例来源:origin: prestodb/presto

private List<Integer> rangeList(int endExclusive)
{
  return IntStream.range(0, endExclusive)
      .boxed()
      .collect(toImmutableList());
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void add_counts_issue_per_component_on_leak_globally_and_per_assignee() {
 List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).collect(Collectors.toList());
 String assignee = randomAlphanumeric(10);
 componentUuids.stream()
  .map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(true))
  .forEach(underTest::add);
 DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT);
 DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.COMPONENT);
 Stream.of(globalDistribution, assigneeDistribution)
  .forEach(distribution -> componentUuids.forEach(componentUuid -> assertStats(distribution, componentUuid, 1, 0, 1)));
}

代码示例来源:origin: SonarSource/sonarqube

private String doHandlePropertySet(DbSession dbSession, SetRequest request, @Nullable PropertyDefinition definition, Optional<ComponentDto> component) {
 validatePropertySet(request, definition);
 int[] fieldIds = IntStream.rangeClosed(1, request.getFieldValues().size()).toArray();
 String inlinedFieldKeys = IntStream.of(fieldIds).mapToObj(String::valueOf).collect(COMMA_JOINER);
 String key = persistedKey(request);
 Long componentId = component.isPresent() ? component.get().getId() : null;
 deleteSettings(dbSession, component, key);
 dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(key).setValue(inlinedFieldKeys).setResourceId(componentId));
 List<String> fieldValues = request.getFieldValues();
 IntStream.of(fieldIds).boxed()
  .flatMap(i -> readOneFieldValues(fieldValues.get(i - 1), request.getKey()).entrySet().stream()
   .map(entry -> new KeyValue(key + "." + i + "." + entry.getKey(), entry.getValue())))
  .forEach(keyValue -> dbClient.propertiesDao().saveProperty(dbSession, toFieldProperty(keyValue, componentId)));
 return inlinedFieldKeys;
}

代码示例来源:origin: AsyncHttpClient/async-http-client

private void allSemaphoresCheckPermitCount(ConnectionSemaphore semaphore, int permitCount, int runnerCount) {
 List<SemaphoreRunner> runners = IntStream.range(0, runnerCount)
     .mapToObj(i -> new SemaphoreRunner(semaphore, PK))
     .collect(Collectors.toList());
 runners.forEach(SemaphoreRunner::acquire);
 runners.forEach(SemaphoreRunner::await);
 long tooManyConnectionsCount = runners.stream().map(SemaphoreRunner::getAcquireException)
     .filter(Objects::nonNull)
     .filter(e -> e instanceof IOException)
     .count();
 long acquired = runners.stream().map(SemaphoreRunner::getAcquireException)
     .filter(Objects::isNull)
     .count();
 int expectedAcquired = permitCount > 0 ? Math.min(permitCount, runnerCount) : runnerCount;
 assertEquals(expectedAcquired, acquired);
 assertEquals(runnerCount - acquired, tooManyConnectionsCount);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void selectByKeys_throws_IAE_when_keys_contains_null() {
 Random random = new Random();
 Set<String> keysIncludingANull = Stream.of(
  IntStream.range(0, random.nextInt(10)).mapToObj(i -> "b_" + i),
  Stream.of((String) null),
  IntStream.range(0, random.nextInt(10)).mapToObj(i -> "a_" + i))
  .flatMap(s -> s)
  .collect(Collectors.toSet());
 expectKeyNullOrEmptyIAE();
 underTest.selectByKeys(dbSession, keysIncludingANull);
}

代码示例来源:origin: biezhi/30-seconds-of-java8

public static List<Object[]> zip(Object[]... arrays) {
  OptionalInt max = Arrays.stream(arrays).mapToInt(arr -> arr.length).max();
  return IntStream.range(0, max.getAsInt())
      .mapToObj(i -> Arrays.stream(arrays)
          .map(arr -> i < arr.length ? arr[i] : null)
          .toArray())
      .collect(Collectors.toList());
}

代码示例来源:origin: shekhargulati/strman-java

/**
 * Aggregates the contents of n strings into a single list of tuples.
 *
 * @param inputs A list of strings.
 * @return A list of strings if none of the strings in the input is null or empty.
 * An empty list otherwise.
 */
public static List<String> zip(String... inputs) {
  if (inputs.length == 0) {
    return Collections.emptyList();
  }
  OptionalInt min = Arrays.stream(inputs).mapToInt(str -> str == null ? 0 : str.length()).min();
  if (!min.isPresent()) {
    return Collections.emptyList();
  }
  return IntStream.range(0, min.getAsInt())
      .mapToObj(elementIndex -> Arrays.stream(inputs)
          .map(input -> String.valueOf(input.charAt(elementIndex)))
          .collect(joining()))
      .collect(toList());
}

代码示例来源:origin: twosigma/beakerx

@Test
 public void shouldLimitListData() {
  //given
  List<List<Number>> integers = new ArrayList<>();
  IntStream.range(1, 1000).forEach(x -> {
   List<Number> collect = IntStream.range(1, 1000).boxed().collect(Collectors.toList());
   integers.add(collect);
  });
  //when
  List<List<Number>> limitedData = sut.limitListData(integers);
  //then
  Assertions.assertThat(sut.totalPoints(limitedData).getAsInt()).isEqualTo(NUMBER_OF_NODES_TO_DISPLAY);
 }
}

代码示例来源:origin: prestodb/presto

@Override
  public ScheduleResult schedule()
  {
    OptionalInt totalPartitions = OptionalInt.of(partitionToNode.size());
    List<RemoteTask> newTasks = IntStream.range(0, partitionToNode.size())
        .mapToObj(partition -> taskScheduler.scheduleTask(partitionToNode.get(partition), partition, totalPartitions))
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(toImmutableList());

    return new ScheduleResult(true, newTasks, 0);
  }
}

代码示例来源:origin: SonarSource/sonarqube

private static Set<String> shuffleWithNonExistentUuids(String... uuids) {
 return Stream.concat(
  IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> randomAlphabetic(9)),
  Arrays.stream(uuids))
  .collect(toSet());
}

代码示例来源:origin: jooby-project/jooby

static List<Map<String, Object>> frames(final ClassLoader loader, final SourceLocator locator,
  final Throwable cause) {
 List<StackTraceElement> stacktrace = Arrays.asList(cause.getStackTrace());
 int limit = IntStream.range(0, stacktrace.size())
   .filter(i -> stacktrace.get(i).getClassName().equals(HANDLER)).findFirst()
   .orElse(stacktrace.size());
 return stacktrace.stream()
   // trunk stack at HttpHandlerImpl (skip servers stack)
   .limit(limit)
   .map(e -> frame(loader, locator, cause, e))
   .collect(Collectors.toList());
}

代码示例来源:origin: apache/ignite

IntStream.range(0, ensembleSize).mapToObj(
    modelIdx -> getMapping(
      featuresVectorSize,
      featureSubspaceDim,
      environment.randomNumbersGenerator().nextLong()))
    .collect(Collectors.toList()) :
  null;
List<DatasetTrainer<IgniteModel<Vector, Double>, L>> subspaceTrainers = IntStream.range(0, ensembleSize)
  .mapToObj(mdlIdx -> {
    AdaptableDatasetTrainer<Vector, Double, Vector, Double, ? extends IgniteModel, L> tr =
      AdaptableDatasetTrainer.of(trainers.get(mdlIdx));
      .withEnvironmentBuilder(envBuilder);
  })
  .map(CompositionUtils::unsafeCoerce)
  .collect(Collectors.toList());
    subspaceTrainers)).afterTrainedModel(l -> aggregator.apply(l.stream().mapToDouble(Double::valueOf).toArray()));

代码示例来源:origin: jtablesaw/tablesaw

private AttributeDataset dataset(NumericColumn<?> responseCol, AttributeType type, List<Column<?>> variableCols) {
  List<Column<?>> convertedVariableCols = variableCols.stream()
    .map(col -> col.type() == ColumnType.STRING ? col : table.nCol(col.name()))
    .collect(Collectors.toList());
  Attribute responseAttribute = type == AttributeType.NOMINAL
    ? colAsNominalAttribute(responseCol) : new NumericAttribute(responseCol.name());
  AttributeDataset dataset = new AttributeDataset(table.name(),
    convertedVariableCols.stream().map(col -> colAsAttribute(col)).toArray(Attribute[]::new),
    responseAttribute);
  for (int i = 0; i < responseCol.size(); i++) {
    final int r = i;
    double[] x = IntStream.range(0, convertedVariableCols.size())
      .mapToDouble(c -> getDouble(convertedVariableCols.get(c), dataset.attributes()[c], r))
      .toArray();
    dataset.add(x, responseCol.getDouble(r));
  }
  return dataset;
}

代码示例来源:origin: prestodb/presto

.map(ImmutableSet::copyOf)
  .collect(toList());
  .mapToInt(Set::size)
  .sum();
newBaseExpressions = Math.multiplyExact(subPredicates.stream()
    .mapToInt(Set::size)
    .reduce(Math::multiplyExact)
    .getAsInt(), subPredicates.size());

代码示例来源:origin: neo4j/neo4j

.map( v -> materializeAnyResult( proxySpi, v ) ).collect( Collectors.toList() ) ) );
    .collect( Collectors.toList() ) );
    .collect( Collectors.toList() ) );
double[] array = ((DoubleStream) anyValue).toArray();
return Values.doubleArray( array );
return VirtualValues.fromList( ((IntStream) anyValue).mapToObj( i -> Values.booleanValue( i != 0 ) ).collect( Collectors.toList() ) );

相关文章

微信公众号

最新文章

更多