java.util.stream.IntStream.forEach()方法的使用及代码示例

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

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

IntStream.forEach介绍

[英]Performs an action for each element of this stream.

This is a terminal operation.

For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
[中]为此流的每个元素执行操作。
这是一个terminal operation
对于并行流管道,此操作保证尊重流的相遇顺序,因为这样做会牺牲并行性的好处。对于任何给定的元素,可以在库选择的任何时间和线程中执行该操作。如果操作访问共享状态,则它负责提供所需的同步。

代码示例

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

/**
 * Creates a VarMap mapping the type parameters of the class used in <tt>type</tt> to their actual value.
 */
private void addAll(TypeVariable<?>[] variables, Type[] values) {
  assert variables.length == values.length;
  IntStream.range(0, variables.length).forEach(i -> map.put(variables[i], values[i]));
}

代码示例来源:origin: google/guava

private static void doParallelCacheOp(int count, IntConsumer consumer) {
 IntStream.range(0, count).parallel().forEach(consumer);
}

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

@Test
public void nextId() {
  // Repeat a few times just to be sure...
  IntStream.rangeClosed(1, 5).forEach(i -> assertNextId());
}

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

@Test
public void verify_118_percent_ratio_for_upper_bound() {
 IntStream.range(0, 1000)
  .forEach(ref -> upperBoundGivesNonMeaningfulScore(ref, 1.18));
}

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

@Test
public void testRingBitSetParallel() {
  System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
  RingBitSet ringBitSet = new RingBitSet(1000);
  IntStream.range(0, 1000).parallel().forEach((i) -> {
    if (i < 500) {
      ringBitSet.setNextBit(true);
    } else {
      ringBitSet.setNextBit(false);
    }
  });
  // The cardinality must be 500
  assertThat(ringBitSet.cardinality()).isEqualTo(500);
  // The size is 1024-bit, because the bits are stored in an array of 16 long values
  assertThat(ringBitSet.size()).isEqualTo(1024);
  // The length must be 1000, because the ring bit set contains 1000 entries
  assertThat(ringBitSet.length()).isEqualTo(1000);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testLoadExistingRecoversInflightInvalidationsForEventualCache() throws Exception {
 ClusterTierActiveEntity activeEntity = new ClusterTierActiveEntity(defaultRegistry, defaultConfiguration, DEFAULT_MAPPER);
 EhcacheStateServiceImpl ehcacheStateService = defaultRegistry.getStoreManagerService();
 ehcacheStateService.createStore(defaultStoreName, defaultStoreConfiguration, false);  //Passive would have done this before failover
 InvalidationTracker invalidationTracker = ehcacheStateService.getInvalidationTracker(defaultStoreName);
 Random random = new Random();
 random.ints(0, 100).limit(10).forEach(invalidationTracker::trackHashInvalidation);
 activeEntity.loadExisting();
 assertThat(activeEntity.getInflightInvalidations().isEmpty(), is(false));
}

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

@Test
public void verify_84_percent_ratio_for_lower_bound() {
 IntStream.range(0, 1000)
  .forEach(ref -> lowerBoundGivesNonMeaningfulScore(ref, 0.84));
}

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

@Test
public void insert_data()  {
 int nbOfInsert = 10 + new Random().nextInt(20);
 List<EsQueueDto> esQueueDtos = new ArrayList<>();
 IntStream.rangeClosed(1, nbOfInsert).forEach(
  i -> esQueueDtos.add(EsQueueDto.create("foo", UuidFactoryFast.getInstance().create()))
 );
 underTest.insert(dbSession, esQueueDtos);
 assertThat(dbTester.countSql(dbSession, "select count(*) from es_queue")).isEqualTo(nbOfInsert);
}

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

public static void repeatChar(AttributedStringBuilder sb, char c, int count) {
  IntStream.range(0, count).forEach(i -> sb.append(c));
}

代码示例来源:origin: ben-manes/caffeine

private static void doParallelCacheOp(int count, IntConsumer consumer) {
 IntStream.range(0, count).parallel().forEach(consumer);
}

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

@Test
public void maxSessions() {
  IntStream.range(0, 10000).forEach(i -> insertSession());
  try {
    insertSession();
    fail();
  }
  catch (IllegalStateException ex) {
    assertEquals("Max sessions limit reached: 10000", ex.getMessage());
  }
}

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

@Test
public void delete_EsQueueDto_does_not_throw_exception() {
 int nbOfInsert = 10 + new Random().nextInt(20);
 List<EsQueueDto> esQueueDtos = new ArrayList<>();
 IntStream.rangeClosed(1, nbOfInsert).forEach(
  i -> esQueueDtos.add(EsQueueDto.create("foo", UuidFactoryFast.getInstance().create()))
 );
 underTest.insert(dbSession, esQueueDtos);
 assertThat(dbTester.countSql(dbSession, "select count(*) from es_queue")).isEqualTo(nbOfInsert);
 underTest.delete(dbSession, esQueueDtos);
 assertThat(dbTester.countSql(dbSession, "select count(*) from es_queue")).isEqualTo(0);
}

代码示例来源: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: ivan-vasilev/neuralnetworks

@Override
public void getNextTarget(Tensor target)
{
  IntStream stream = IntStream.range(0, currentArrays.size());
  if (properties.getParallelPreprocessing())
  {
    stream = stream.parallel();
  }
  stream.forEach(i -> {
    float[] t = getNextTarget(augmentedToRaw.get(arrayToAugmented.get(currentArrays.get(i))));
    if (t != null)
    {
      System.arraycopy(t, 0, target.getElements(), target.getStartIndex() + i * getTargetDimensions(), t.length);
    }
  });
}

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

@Test
public void create_allows_multiple_calls_with_same_ordinal() {
 IntStream.range(0, new Random().nextInt(50)).forEach(ignored -> {
  CeWorker ceWorker = underTest.create(randomOrdinal);
  assertThat(ceWorker.getOrdinal()).isEqualTo(randomOrdinal);
 });
}

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

@Test
public void testCartesianProduct() {
  Multimap<User, Article> product = HashMultimap.create();
  h.createQuery("SELECT * FROM user, article")
    .map(JoinRowMapper.forTypes(User.class, Article.class))
    .forEach(jr -> product.put(jr.get(User.class), jr.get(Article.class)));
  Multimap<User, Article> expected = HashMultimap.create();
  IntStream.rangeClosed(1, 3).forEach(u ->
    IntStream.rangeClosed(1, 3).forEach(a ->
      expected.put(u(u), a(a))));
  assertThat(product).isEqualTo(expected);
}

代码示例来源:origin: iluwatar/java-design-patterns

IntStream.range(0, 5)
  .forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock(), 
    ThreadLocalRandom.current().nextLong(5000))));
LOGGER.info("Writers added...");
IntStream.range(0, 5)
  .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), 
    ThreadLocalRandom.current().nextLong(10))));
LOGGER.info("Readers added...");
IntStream.range(6, 10)
  .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), 
    ThreadLocalRandom.current().nextLong(10))));
LOGGER.info("More readers added...");

代码示例来源:origin: ivan-vasilev/neuralnetworks

@Override
  public void value(Tensor inputOutput)
  {
    int sampleLength = inputOutput.getSize() / inputOutput.getDimensions()[0];
    IntStream.range(0, inputOutput.getSize()).parallel().forEach(i -> inputOutput.getElements()[inputOutput.getStartIndex() + i] -= meanValues[i % sampleLength]);
  }
}

代码示例来源:origin: real-logic/aeron

@Test
  public void shouldNotExceedTmaxBackoff()
  {
    IntStream.range(0, 100000).forEach(
      (i) ->
      {
        final double delay = generator.generateNewOptimalDelay();
        assertThat(delay, lessThanOrEqualTo((double)MAX_BACKOFF));
      });
  }
}

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

@Test
public void delete_unknown_EsQueueDto_does_not_throw_exception() {
 int nbOfInsert = 10 + new Random().nextInt(20);
 List<EsQueueDto> esQueueDtos = new ArrayList<>();
 IntStream.rangeClosed(1, nbOfInsert).forEach(
  i -> esQueueDtos.add(EsQueueDto.create("foo", UuidFactoryFast.getInstance().create()))
 );
 underTest.insert(dbSession, esQueueDtos);
 underTest.delete(dbSession, EsQueueDto.create("foo", UuidFactoryFast.getInstance().create()));
 assertThat(dbTester.countSql(dbSession, "select count(*) from es_queue")).isEqualTo(nbOfInsert);
}

相关文章