java.util.stream.IntStream Java Examples

The following examples show how to use java.util.stream.IntStream. 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: CompletableFuturesTest.java    From protonpack with MIT License 6 votes vote down vote up
@Test
public void collectsValuesFromCompletableFutures() throws ExecutionException, InterruptedException {
    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    CompletableFuture<List<Integer>> integers = IntStream.range(0, 1000)
            .mapToObj(i -> CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(random.nextInt(100));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return i;
            }, threadPool))
            .collect(CompletableFutures.toFutureList());

    assertThat(
            integers.get(),
            equalTo(IntStream.range(0, 1000).mapToObj(Integer::valueOf).collect(toList())));
}
 
Example #2
Source File: LogServiceCluster.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a number of worker nodes with random ports and start them
 * @param numWorkers number of Workers to create
 */
public void createWorkers(int numWorkers) {
    String meta = getMetaIdentity();
    List<LogServer> newWorkers = IntStream.range(0, numWorkers).parallel().mapToObj(i ->
            LogServer.newBuilder()
                    .setHostName("localhost")
                    .setPort(10000 + i)
                    .setMetaQuorum(meta)
                    .setWorkingDir(baseTestDir + "/workers/" + i)
                    .build()).collect(Collectors.toList());
    newWorkers.parallelStream().forEach( worker -> {
        try {
            worker.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    workers.addAll(newWorkers);
}
 
Example #3
Source File: TrackSegmentTest.java    From jpx with Apache License 2.0 6 votes vote down vote up
@Test
public void map() {
	final TrackSegment segment = TrackSegment.of(
		IntStream.range(0, 50)
			.mapToObj(i -> WayPoint.builder().build(i, i))
			.collect(Collectors.toList())
	);

	final TrackSegment mapped = segment.toBuilder()
		.map(wp -> wp.toBuilder()
			.lat(wp.getLatitude().doubleValue() + 1)
			.build())
		.build();

	for (int i = 0, n = mapped.getPoints().size(); i < n; ++i) {
		Assert.assertEquals(
			mapped.getPoints().get(i).getLatitude().doubleValue(),
			(double)(i + 1)
		);
	}
}
 
Example #4
Source File: FilterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void breadthFirstVisitShouldAllowUpToLimitNesting() {
    FilterCondition condition = FilterCondition.builder()
        .to("[email protected]")
        .build();

    Filter nestedFilter = IntStream.range(0, 10).boxed().reduce(
        (Filter) condition,
        (filter, i) -> FilterOperator.and(filter),
        (f1, f2) -> {
            throw new RuntimeException("unsupported combination");
        });

    assertThat(nestedFilter.breadthFirstVisit())
        .containsExactly(condition);
}
 
Example #5
Source File: HighFrequencyDetector.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private int computeTimeDelta(List<Metric> list) {
  int size = list.size();
  IntSummaryStatistics stats = IntStream.range(1, size)
      .map(
          x ->
              (int)
                  (list.get(size - x).getTime().getTime()
                      - list.get(size - x - 1).getTime().getTime()))
      .filter(d -> (d >= 0 && d < minFrequencyMillisAllowed))
      .summaryStatistics();

  int result = -1;

  /**
   * In order to be marked as high frequency metric the number of points
   * should be above the BURST_THRESHOLD.
   * It ignores any small bursts of high frequency metrics.
   */
  if (stats.getCount() > BURST_THRESHOLD) {
    // uses minimal delta time from all consecutive data points
    result = stats.getMin();
    log.info("stats: " + stats);
  }
  return result;
}
 
Example #6
Source File: ArffDatasetAdapter.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void serializeData(final BufferedWriter bw, final ILabeledDataset<? extends ILabeledInstance> data) throws IOException {
	bw.write(EArffItem.DATA.getValue() + "\n");
	for (ILabeledInstance instance : data) {
		if (instance instanceof DenseInstance) {
			Object[] atts = instance.getAttributes();
			bw.write(IntStream.range(0, atts.length).mapToObj(x -> serializeAttributeValue(data.getInstanceSchema().getAttribute(x), atts[x])).collect(Collectors.joining(",")));
			bw.write(",");
			bw.write(serializeAttributeValue(data.getInstanceSchema().getLabelAttribute(), instance.getLabel()));
			bw.write("\n");
		} else {
			bw.write("{");
			bw.write(((SparseInstance) instance).getAttributeMap().entrySet().stream().map(x -> x.getKey() + " " + serializeAttributeValue(data.getInstanceSchema().getAttribute(x.getKey()), x.getValue()))
					.collect(Collectors.joining(",")));
			if (instance.isLabelPresent()) {
				bw.write(",");
			}
			bw.write(data.getNumAttributes());
			bw.write(" ");
			bw.write(serializeAttributeValue(data.getInstanceSchema().getLabelAttribute(), instance.getLabel()));
			bw.write("}\n");
		}
	}
}
 
Example #7
Source File: DataIndexOnlyIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataIndexOnlyOnCustomType() throws Exception {
  final DataStore dataStore = dataIdxOnlyDataStoreOptions.createDataStore();
  final LatLonTimeAdapter adapter = new LatLonTimeAdapter();
  dataStore.addType(adapter);
  try (Writer<LatLonTime> writer = dataStore.createWriter(adapter.getTypeName())) {
    for (int i = 0; i < 10; i++) {
      writer.write(new LatLonTime(i, 100 * i, 0.25f * i, -0.5f * i));
    }
  }

  final Set<Integer> expectedIntIds =
      IntStream.rangeClosed(0, 9).boxed().collect(Collectors.toSet());
  try (CloseableIterator<LatLonTime> it =
      (CloseableIterator) dataStore.query(QueryBuilder.newBuilder().build())) {
    while (it.hasNext()) {
      Assert.assertTrue(expectedIntIds.remove(it.next().getId()));
    }
  }
  Assert.assertTrue(expectedIntIds.isEmpty());
  TestUtils.deleteAll(dataIdxOnlyDataStoreOptions);
}
 
Example #8
Source File: HMMSegmentProcessor.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Calculates the posterior expectation of the mean of hidden state values on a segment
 *
 * @param firstTargetIndex first target index of the segment
 * @param segmentLength length of the segment
 * @param fbResult result of forward-backward algorithm
 * @param <STATE> type of hidden state; must implement {@link ScalarProducer}
 * @param <TARGET> type of target; must implement {@link Locatable}
 * @throws IllegalStateException if segment length is negative
 * @return segment mean
 */
public static <STATE extends ScalarProducer, TARGET extends Locatable> double calculateSegmentMean(
        final int firstTargetIndex,
        final int segmentLength,
        final ForwardBackwardAlgorithm.Result<?, TARGET, STATE> fbResult) {
    Utils.validateArg(segmentLength >= 0, "Segment length must be non-negative");
    /* trivial case when the segment has length 0 */
    if (segmentLength == 0) {
        return Double.NaN;
    } else {
        final List<STATE> hiddenStates = fbResult.model().hiddenStates();
        final double[] hiddenStateValues = hiddenStates.stream()
                .mapToDouble(STATE::getScalar)
                .toArray();
        return IntStream.range(firstTargetIndex, firstTargetIndex + segmentLength).boxed()
                .flatMapToDouble(targetIndex -> IntStream.range(0, hiddenStates.size())
                        .mapToDouble(si -> hiddenStateValues[si] *
                                FastMath.exp(fbResult.logProbability(targetIndex, hiddenStates.get(si)))))
                .sum() / segmentLength;
    }
}
 
Example #9
Source File: BitSetStreamTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandomStream() {
    final int size = 1024 * 1024;
    final int[] seeds = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
            43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
    final byte[] bytes = new byte[size];
    for (int seed : seeds) {
        final Random random = new Random(seed);
        random.nextBytes(bytes);
        final BitSet bitSet = BitSet.valueOf(bytes);
        final int cardinality = bitSet.cardinality();
        final IntStream stream = bitSet.stream();
        final int[] array = stream.toArray();
        assertEquals(array.length, cardinality);
        int nextSetBit = -1;
        for (int i=0; i < cardinality; i++) {
            nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
            assertEquals(array[i], nextSetBit);
        }
    }
}
 
Example #10
Source File: FunctionInvocationClientTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
public void createOrders() {

		Random random = new Random();
		Address address = new Address("it", "doesn't", "matter");

		LongStream.rangeClosed(1, 100).forEach((orderId) -> LongStream.rangeClosed(1, 3).forEach((customerId) -> {
			Order order = new Order(orderId, customerId, address);
			IntStream.rangeClosed(0, random.nextInt(3) + 1).forEach((lineItemCount) -> {
				int quantity = random.nextInt(3) + 1;
				long productId = random.nextInt(3) + 1;
				order.add(new LineItem(productRepository.findById(productId).get(), quantity));
			});
			orderRepository.save(order);
		}));

		assertThat(orders.keySetOnServer().size()).isEqualTo(100);
	}
 
Example #11
Source File: SerializableTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void test2c() {
    ChronicleMap<Integer, Bar2> map = ChronicleMapBuilder.simpleMapOf(Integer.class, Bar2.class)
            .name("bar")
            .averageValueSize(1024)
            .entries(10)
            .create();

    String expected = IntStream.range(0, 4096)
            .mapToObj(i -> i % 50 == 0 ? String.format("\n%04d", i) : "" + i % 10)
            .collect(Collectors.joining(""));

    Bar2 value = new Bar2(expected);
    map.put(1, value);
    String actual = map.get(1).x;

    assertEquals(expected, actual);
}
 
Example #12
Source File: ExceptionController.java    From yue-library with Apache License 2.0 6 votes vote down vote up
/**
 * Flux : 返回0-n个元素 注:需要指定MediaType
 * 
 * @return
 */
@GetMapping(value = "/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
private Flux<String> flux() {
	Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
		if (i == 3) {
			throw new ResultException("flux 错误测试");
		}
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
		}
		return "flux data--" + i;
	}));
	
	return result;
}
 
Example #13
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public void mouseDragged(MouseEvent e) {
  JList<?> l = (JList<?>) e.getComponent();
  l.setFocusable(true);
  Point destPoint = e.getPoint();
  Path2D rb = getRubberBand();
  rb.reset();
  rb.moveTo(srcPoint.x, srcPoint.y);
  rb.lineTo(destPoint.x, srcPoint.y);
  rb.lineTo(destPoint.x, destPoint.y);
  rb.lineTo(srcPoint.x, destPoint.y);
  rb.closePath();

  int[] indices = IntStream.range(0, l.getModel().getSize())
      .filter(i -> rb.intersects(l.getCellBounds(i, i))).toArray();
  l.setSelectedIndices(indices);
  l.repaint();
}
 
Example #14
Source File: TestRaftServerConfigKeys.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the value to <code>raft.server.storage.dir</code> via
 * RaftServerConfigKeys and verifies it by reading directly from property.
 */
@Test
public void testStorageDirProperty() {
  final File testDir = new File(
      rootTestDir.get(), UUID.randomUUID().toString());
  final List<File> directories = new ArrayList<>();
  final  RaftProperties properties = new RaftProperties();

  IntStream.range(0, 10).mapToObj((i) -> new File(testDir,
      Integer.toString(i))).forEach(directories::add);
  RaftServerConfigKeys.setStorageDir(properties, directories);

  final String expected = directories.stream().map(File::getAbsolutePath)
      .collect(Collectors.joining(","));
  final String actual = properties.get(RaftServerConfigKeys.STORAGE_DIR_KEY);
  Assert.assertEquals(expected, actual);
}
 
Example #15
Source File: MAPInference.java    From toolbox with Apache License 2.0 5 votes vote down vote up
private double estimateProbabilityOfPartialAssignment(Assignment MAPassignment, boolean useConditionalDistributions) {

        double probabilityEstimate;
        final int numSamplesAverage = 150;

        Assignment evidenceAugmented=new HashMapAssignment(evidence);
        MAPvariables.forEach(voi -> evidenceAugmented.setValue(voi, MAPassignment.getValue(voi)));

        final Assignment finalAssignment=new HashMapAssignment(MAPassignment);

        IntStream auxIntStream = IntStream.range(0, numSamplesAverage);
        //probabilityEstimate = auxIntStream.mapToObj(i -> obtainValuesRandomly(finalAssignment,evidenceAugmented,new Random())).mapToDouble(as -> Math.exp(this.model.getLogProbabiltyOf(as))).average().getAsDouble();
        try {
            probabilityEstimate = auxIntStream.mapToObj(i -> {
                if (useConditionalDistributions)
                    return obtainValues(finalAssignment, evidenceAugmented, new Random(MAPrandom.nextInt()));
                else
                    return obtainValuesRandomly(finalAssignment, evidenceAugmented, new Random(MAPrandom.nextInt()));
                })
                .mapToDouble(as -> Math.exp(this.model.getLogProbabiltyOf(as)))
                .filter(Double::isFinite).average().getAsDouble();
        }
        catch(Exception e) {
            probabilityEstimate=0;
        }

        return probabilityEstimate;
    }
 
Example #16
Source File: GermlineCNVIntervalVariantComposerUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Assert that exception is thrown if normalized posterior probabilities do not add up to 1
 */
@Test(expectedExceptions = IllegalArgumentException.class)
public void testCopyNumberPosteriorDistributionValidation() {
    new CopyNumberPosteriorDistribution(IntStream.range(0, TEST_INVALID_LOG_POSTERIOR_VECTOR.length)
            .boxed()
            .collect(Collectors.toMap(IntegerCopyNumberState::new,
                    cn -> TEST_INVALID_LOG_POSTERIOR_VECTOR[cn])));
}
 
Example #17
Source File: GroupImpl.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setPlotMaxXList(final @NotNull List<Optional<Double>> values) {
	if(values.size() == shapes.size()) {
		IntStream.range(0, values.size()).
			filter(i -> values.get(i).isPresent() && shapes.get(i) instanceof PlotProp).
			forEach(i -> ((PlotProp) shapes.get(i)).setPlotMaxX(values.get(i).orElseThrow()));
	}
}
 
Example #18
Source File: GroupImpl.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setGridStartList(final @NotNull List<Optional<Point>> values) {
	if(values.size() == shapes.size()) {
		IntStream.range(0, values.size()).
			filter(i -> values.get(i).isPresent() && shapes.get(i) instanceof IStdGridProp).
			forEach(i -> ((IStdGridProp) shapes.get(i)).setGridStart(values.get(i).orElseThrow().getX(),  values.get(i).orElseThrow().getY()));
	}
}
 
Example #19
Source File: ModelRunner.java    From SLP-Core with MIT License 5 votes vote down vote up
protected List<Double> predictSequence(List<Integer> tokens) {
	if (this.selfTesting) this.model.forget(tokens);
	List<List<Integer>> preds = toPredictions(this.model.predict(tokens));
	List<Double> mrrs = IntStream.range(0, tokens.size())
			.mapToObj(i -> preds.get(i).indexOf(tokens.get(i)))
			.map(ModelRunner::toMRR)
			.collect(Collectors.toList());
	if (this.selfTesting) this.model.learn(tokens);
	return mrrs;
}
 
Example #20
Source File: MatchOpTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testIntStreamMatches() {
    assertIntPredicates(() -> IntStream.range(0, 0), Kind.ANY, INT_PREDICATES, false, false, false, false);
    assertIntPredicates(() -> IntStream.range(0, 0), Kind.ALL, INT_PREDICATES, true, true, true, true);
    assertIntPredicates(() -> IntStream.range(0, 0), Kind.NONE, INT_PREDICATES, true, true, true, true);

    assertIntPredicates(() -> IntStream.range(1, 2), Kind.ANY, INT_PREDICATES, true, false, false, true);
    assertIntPredicates(() -> IntStream.range(1, 2), Kind.ALL, INT_PREDICATES, true, false, false, true);
    assertIntPredicates(() -> IntStream.range(1, 2), Kind.NONE, INT_PREDICATES, false, true, true, false);

    assertIntPredicates(() -> IntStream.range(1, 6), Kind.ANY, INT_PREDICATES, true, false, true, true);
    assertIntPredicates(() -> IntStream.range(1, 6), Kind.ALL, INT_PREDICATES, true, false, false, false);
    assertIntPredicates(() -> IntStream.range(1, 6), Kind.NONE, INT_PREDICATES, false, true, false, false);
}
 
Example #21
Source File: StreamBuilderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testDoubleAfterBuilding(int size) {
    DoubleStream.Builder sb = DoubleStream.builder();
    IntStream.range(0, size).asDoubleStream().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example #22
Source File: TestDictionaryAwarePageFilter.java    From presto with Apache License 2.0 5 votes vote down vote up
private static IntSet toSet(SelectedPositions selectedPositions)
{
    int start = selectedPositions.getOffset();
    int end = start + selectedPositions.size();
    if (selectedPositions.isList()) {
        return new IntArraySet(Arrays.copyOfRange(selectedPositions.getPositions(), start, end));
    }
    return new IntArraySet(IntStream.range(start, end).toArray());
}
 
Example #23
Source File: AutogenS3DatasetDiff.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null) return false;
  if (!(o instanceof AutogenS3DatasetDiff)) return false;
  AutogenS3DatasetDiff other = (AutogenS3DatasetDiff) o;

  {
    Function3<List<AutogenS3DatasetComponentDiff>, List<AutogenS3DatasetComponentDiff>, Boolean>
        f =
            (x2, y2) ->
                IntStream.range(0, Math.min(x2.size(), y2.size()))
                    .mapToObj(
                        i -> {
                          Function3<
                                  AutogenS3DatasetComponentDiff,
                                  AutogenS3DatasetComponentDiff,
                                  Boolean>
                              f2 = (x, y) -> x.equals(y);
                          return f2.apply(x2.get(i), y2.get(i));
                        })
                    .filter(x -> x.equals(false))
                    .collect(Collectors.toList())
                    .isEmpty();
    if (this.Components != null || other.Components != null) {
      if (this.Components == null && other.Components != null) return false;
      if (this.Components != null && other.Components == null) return false;
      if (!f.apply(this.Components, other.Components)) return false;
    }
  }
  return true;
}
 
Example #24
Source File: NormalizeUtils.java    From jMetal with MIT License 5 votes vote down vote up
/**
 * Normalizes a vector of double values
 *
 * @param vector
 * @return The normalized vector
 */
public static double[] getNormalizedVector(double[] vector, double min, double max) {
  double[] normalizedVector = new double[vector.length];

  IntStream.range(0, vector.length)
          .forEach(i -> normalizedVector[i] = normalize(vector[i], min, max));

  return normalizedVector;
}
 
Example #25
Source File: AsyncProducerTutorial.java    From pulsar-java-tutorial with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws PulsarClientException {
    PulsarClient client = PulsarClient.builder()
            .serviceUrl(SERVICE_URL)
            .build();

    log.info("Created a client for the Pulsar cluster running at {}", SERVICE_URL);

    client.newProducer()
            .topic(TOPIC_NAME)
            .compressionType(CompressionType.LZ4)
            .createAsync()
            .thenAccept(producer -> {
                log.info("Producer created asynchronously for the topic {}", TOPIC_NAME);

                MessageBuilder<byte[]> msgBuilder = MessageBuilder.create();

                // Send 10 messages with varying content
                IntStream.range(1, 11).forEach(i -> {
                    byte[] msgContent = String.format("hello-pulsar-%d", i).getBytes();
                    msgBuilder.setContent(msgContent);
                    producer.sendAsync(msgBuilder.build())
                            .handle((msgId, e) -> {
                                if (e != null) {
                                    e.printStackTrace();
                                }

                                log.info("Successfully produced message with ID {}",
                                        new String(msgId.toByteArray()));
                                return null;
                            });
                });
            })
            .exceptionally(e -> {
                log.error(e.toString());
                return null;
            });
}
 
Example #26
Source File: FtpTransportServiceComponent.java    From carbon-kernel with Apache License 2.0 5 votes vote down vote up
private void registerSkippedTransports(BundleContext bundleContext) {
    IntStream.range(0, SKIPPED_SERVICE_COUNT)
            .forEach($ -> {
                Dictionary<String, Object> properties = new Hashtable<>();
                properties.put("skipCarbonStartupResolver", true);
                bundleContext.registerService(Transport.class, new FtpTransport(), properties);
            });
}
 
Example #27
Source File: LeastConnHostSelectorTest.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectHost() throws Exception {
    assertThat(leastConnHostSelector, instanceOf(StrictLeastConnHostSelector.class));
    for (int retry = 1; retry <= NUM_RETRIES; retry++) {
        int hostsLength = new Random().nextInt(NUM_HOSTS);
        IntStream.range(0, hostsLength - 1).forEach(x -> {
            final Host[] newHosts = Arrays.copyOf(hosts, hostsLength);
            long result = leastConnHostSelector.selectHost(newHosts, commonExchange);
            assertThat(result, equalTo(0L));
        });
    }
}
 
Example #28
Source File: LocalDataPartitionerTest.java    From systemds with Apache License 2.0 5 votes vote down vote up
private static List<MatrixBlock> generateExpectedDataDR(MatrixBlock mb, MatrixBlock perm) {
	int batchSize = (int) Math.ceil((double) ROW_SIZE / WORKER_NUM);
	return IntStream.range(0, WORKER_NUM).mapToObj(i -> {
		int begin = i * batchSize;
		int end = Math.min((i + 1) * batchSize, mb.getNumRows());
		MatrixBlock slicedPerm = perm.slice(begin, end - 1);
		return slicedPerm.aggregateBinaryOperations(slicedPerm, mb, new MatrixBlock(),
				InstructionUtils.getMatMultOperator(WORKER_NUM));
	}).collect(Collectors.toList());
}
 
Example #29
Source File: MultiCreateFromEmitterTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithDropBackPressure() {
    MultiAssertSubscriber<Integer> subscriber = Multi.createFrom().<Integer> emitter(emitter -> {
        IntStream.range(0, 1000).forEach(emitter::emit);
        emitter.complete();
    }, BackPressureStrategy.DROP).subscribe()
            .withSubscriber(MultiAssertSubscriber.create(20))
            .request(Long.MAX_VALUE)
            .assertCompletedSuccessfully();
    // 20 because the 20 first are consumed, others are dropped
    assertThat(subscriber.items()).hasSize(20);

    subscriber = Multi.createFrom().<Integer> emitter(emitter -> {
        IntStream.range(0, 1000).forEach(emitter::emit);
        emitter.complete();
    }, BackPressureStrategy.DROP).subscribe()
            .withSubscriber(MultiAssertSubscriber.create())
            .request(20)
            .request(Long.MAX_VALUE)
            .assertCompletedSuccessfully();
    assertThat(subscriber.items()).isEmpty();

    Multi.createFrom().<Integer> emitter(MultiEmitter::complete, BackPressureStrategy.DROP)
            .subscribe().withSubscriber(MultiAssertSubscriber.create(20))
            .assertCompletedSuccessfully()
            .assertHasNotReceivedAnyItem();

    Multi.createFrom().<Integer> emitter(emitter -> {
        IntStream.range(0, 1000).forEach(emitter::emit);
        emitter.fail(new IOException("boom"));
    }, BackPressureStrategy.DROP).subscribe()
            .withSubscriber(MultiAssertSubscriber.create())
            .request(20)
            .request(Long.MAX_VALUE)
            .assertHasFailedWith(IOException.class, "boom")
            .assertHasNotReceivedAnyItem();
}
 
Example #30
Source File: DistinctOpTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOp(String name, TestData.OfRef<Integer> data) {
    Collection<Integer> result = exerciseOpsInt(
            data,
            Stream::distinct,
            IntStream::distinct,
            LongStream::distinct,
            DoubleStream::distinct);

    assertUnique(result);
    assertTrue((data.size() > 0) ? result.size() > 0 : result.size() == 0);
    assertTrue(result.size() <= data.size());
}