下面列出了怎么用java.util.stream.IntStream的API类实例代码及写法,或者点击链接到github查看源代码。
@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())));
}
/**
* 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);
}
@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)
);
}
}
@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);
}
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;
}
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");
}
}
}
@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);
}
/**
* 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;
}
}
@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);
}
}
}
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);
}
@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);
}
/**
* 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;
}
@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();
}
/**
* 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);
}
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;
}
/**
* 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])));
}
@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()));
}
}
@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()));
}
}
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;
}
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);
}
@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());
}
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());
}
@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;
}
/**
* 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;
}
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;
});
}
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);
});
}
@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));
});
}
}
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());
}
@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();
}
@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());
}