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: FilterTest.java From james-project with Apache License 2.0 | 6 votes |
@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 #2
Source File: SerializableTest.java From Chronicle-Map with Apache License 2.0 | 6 votes |
@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 #3
Source File: FunctionInvocationClientTests.java From spring-data-examples with Apache License 2.0 | 6 votes |
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 #4
Source File: TestRaftServerConfigKeys.java From incubator-ratis with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: MainPanel.java From java-swing-tips with MIT License | 6 votes |
@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 #6
Source File: BitSetStreamTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@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 #7
Source File: CompletableFuturesTest.java From protonpack with MIT License | 6 votes |
@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 #8
Source File: HighFrequencyDetector.java From ffwd with Apache License 2.0 | 6 votes |
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 #9
Source File: ArffDatasetAdapter.java From AILibs with GNU Affero General Public License v3.0 | 6 votes |
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 #10
Source File: LogServiceCluster.java From incubator-ratis with Apache License 2.0 | 6 votes |
/** * 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 #11
Source File: ExceptionController.java From yue-library with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: HMMSegmentProcessor.java From gatk-protected with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 #13
Source File: DataIndexOnlyIT.java From geowave with Apache License 2.0 | 6 votes |
@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 #14
Source File: TrackSegmentTest.java From jpx with Apache License 2.0 | 6 votes |
@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 #15
Source File: TestVarArgsToArrayAdapterGenerator.java From presto with Apache License 2.0 | 5 votes |
@Test public void testArrayElements() { assertFunction("var_args_sum()", INTEGER, 0); assertFunction("var_args_sum(1)", INTEGER, 1); assertFunction("var_args_sum(1, 2)", INTEGER, 3); assertFunction("var_args_sum(null)", INTEGER, null); assertFunction("var_args_sum(1, null, 2, null, 3)", INTEGER, null); assertFunction("var_args_sum(1, 2, 3)", INTEGER, 6); // var_args_sum(1, 2, 3, ..., k) int k = 100; int expectedSum = (1 + k) * k / 2; assertFunction(format("var_args_sum(%s)", Joiner.on(",").join(IntStream.rangeClosed(1, k).boxed().collect(toSet()))), INTEGER, expectedSum); }
Example #16
Source File: StreamBuilderTest.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
private void testIntStreamBuilder(int size, Function<Integer, IntStream> supplier) { TestData.OfInt data = TestData.Factory.ofIntSupplier(String.format("[0, %d)", size), () -> supplier.apply(size)); withData(data). stream(s -> s). expectedResult(IntStream.range(0, size).toArray()). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(IntStream.range(0, size).toArray()). exercise(); }
Example #17
Source File: FixedSizePreloadCache.java From cloudbreak with Apache License 2.0 | 5 votes |
public FixedSizePreloadCache(int maxSize, Supplier<E> generator) { stack = new Stack<>(); this.maxSize = maxSize; this.generator = generator; IntStream.range(0, maxSize).parallel().forEach(i -> push(generator.get())); }
Example #18
Source File: ChannelFlowManagerTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Test public void testFlowNotDisabledWhenHighLevelNotExceeded() throws Exception { IntStream.rangeClosed(1, 10) .forEach(i -> channelFlowManager.notifyMessageAddition(ctx)); Mockito.verify(ctx, Mockito.never()).writeAndFlush(argumentCaptor.capture()); }
Example #19
Source File: EventNameManager.java From alf.io with GNU General Public License v3.0 | 5 votes |
private String generateRandomName() { return IntStream.range(0, 5) .mapToObj(i -> RandomStringUtils.randomAlphanumeric(15)) .filter(this::isUnique) .limit(1) .findFirst() .orElse(""); }
Example #20
Source File: ConcurrentContainsKeyTest.java From hottub with GNU General Public License v2.0 | 5 votes |
@Test public void testContainsKey() { X[] content = IntStream.range(0, N).mapToObj(i -> new X(i)).toArray(X[]::new); // Create map with an initial size >= ConcurrentHashMap.TREEIFY_THRESHOLD // ensuring tree'ification will occur for a small number of entries // with the same hash code ConcurrentHashMap<Object, Object> m = new ConcurrentHashMap<>(64); Stream.of(content).forEach(x -> m.put(x, x)); test(content, m); }
Example #21
Source File: TextGridBuilderImpl.java From VocabHunter with Apache License 2.0 | 5 votes |
private Map<Integer, Integer> countMap(final List<GridLine> lines) { Map<Integer, Integer> counts = new TreeMap<>(); for (GridLine line : lines) { List<GridCell> cells = line.getCells(); IntStream.range(0, cells.size()).forEach(i -> addToCounts(counts, i, cells.get(i))); } return counts; }
Example #22
Source File: EtlExecutorFactoryUnboundFixedThreadsTest.java From pocket-etl with Apache License 2.0 | 5 votes |
@Test public void executorCanDoRealWork() throws Exception { AtomicInteger workCounter = new AtomicInteger(0); IntStream.range(0, 100).forEach(i -> etlExecutor.submit(workCounter::incrementAndGet, null)); etlExecutor.shutdown(); assertThat(workCounter.get(), equalTo(100)); }
Example #23
Source File: MLSparseMatrixFlat.java From RecSys2018 with Apache License 2.0 | 5 votes |
@Override public void applyRowNorm(final MLDenseVector rowNorm) { IntStream.range(0, this.getNRows()).parallel().forEach(rowIndex -> { if (this.indexes[rowIndex] == MISSING_ROW) { return; } float norm = rowNorm.getValue(rowIndex); if (norm > 1e-5f) { this.values[rowIndex] /= norm; } }); }
Example #24
Source File: EtlExecutorFactoryBlockingFixedThreadsTest.java From pocket-etl with Apache License 2.0 | 5 votes |
@Test public void executorCanDoRealWork() throws Exception { AtomicInteger workCounter = new AtomicInteger(0); IntStream.range(0, 100).forEach(i -> etlExecutor.submit(workCounter::incrementAndGet, null)); etlExecutor.shutdown(); assertThat(workCounter.get(), equalTo(100)); }
Example #25
Source File: CharSequence.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * Returns a stream of {@code int} zero-extending the {@code char} values * from this sequence. Any char which maps to a <a * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code * point</a> is passed through uninterpreted. * * <p>If the sequence is mutated while the stream is being read, the * result is undefined. * * @return an IntStream of char values from this sequence * @since 1.8 */ public default IntStream chars() { class CharIterator implements PrimitiveIterator.OfInt { int cur = 0; public boolean hasNext() { return cur < length(); } public int nextInt() { if (hasNext()) { return charAt(cur++); } else { throw new NoSuchElementException(); } } @Override public void forEachRemaining(IntConsumer block) { for (; cur < length(); cur++) { block.accept(charAt(cur)); } } } return StreamSupport.intStream(() -> Spliterators.spliterator( new CharIterator(), length(), Spliterator.ORDERED), Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, false); }
Example #26
Source File: ParallelSuffixArray.java From phrasal with GNU General Public License v3.0 | 5 votes |
/** * Sort the bitext in parallel. * * @param bitext * @param numPositions * @return */ private int[] build(final int[] bitext, int numPositions) { return IntStream.range(0, bitext.length).parallel().boxed().sorted((x,y) -> { // Compare suffixes int xPos = x, yPos = y, xId = bitext[x], yId = bitext[y]; // Check to see if these points are sentence boundaries if (xId < 0 && yId < 0) { return 0; } else if (xId < 0) { // Say that sentence boundaries are longer than everything else. // They will be pushed to the end of the stream so that limit() can filter them. return 1; } else if (yId < 0) { return -1; } while(xId >= 0 && yId >= 0) { if (xId == yId) { xId = bitext[++xPos]; yId = bitext[++yPos]; } else { // Lexicographic sort return vocabulary.get(xId).compareTo(vocabulary.get(yId)); } } // Compare lengths int xLength = xPos - x + (xId < 0 ? 0 : 1); int yLength = yPos - y + (yId < 0 ? 0 : 1); return xLength - yLength; }).limit(numPositions).mapToInt(i -> i).toArray(); }
Example #27
Source File: CBMCalibration.java From pyramid with Apache License 2.0 | 5 votes |
public static Map<Integer,IsotonicRegression> cardinalityBased(CBM cbm, List<MultiLabel> support, MultiLabelClfDataSet valid) { Map<Integer,IsotonicRegression> calibrations = new HashMap<>(); AccPredictor accPredictor = new AccPredictor(cbm); accPredictor.setComponentContributionThreshold(0.001); Set<Integer> cardinalities = new HashSet<>(); for (MultiLabel multiLabel: support){ cardinalities.add(multiLabel.getNumMatchedLabels()); } for (int cardinality: cardinalities){ Stream<Pair<Double,Double>> stream = IntStream.range(0, valid.getNumDataPoints()).parallel() .boxed().flatMap(i-> { MultiLabel pre = accPredictor.predict(valid.getRow(i)); Set<MultiLabel> copy = new HashSet<>(support); if (!copy.contains(pre)) { copy.add(pre); } List<MultiLabel> candidate = new ArrayList<>(copy); final List<MultiLabel> filtered = candidate.stream().filter(a->a.getNumMatchedLabels()==cardinality).collect(Collectors.toList()); double[] probs = cbm.predictAssignmentProbs(valid.getRow(i), filtered, 0.001); Stream<Pair<Double,Double>> pairs = IntStream.range(0, filtered.size()) .mapToObj(a -> { Pair<Double, Double> pair = new Pair<>(); pair.setFirst(probs[a]); pair.setSecond(0.0); if (filtered.get(a).equals(valid.getMultiLabels()[i])) { pair.setSecond(1.0); } return pair; }); return pairs; }); calibrations.put(cardinality, new IsotonicRegression(stream,false)); } return calibrations; }
Example #28
Source File: Regressor.java From pyramid with Apache License 2.0 | 5 votes |
default double[] predict(DataSet dataSet, boolean parallel){ IntStream intStream = IntStream.range(0, dataSet.getNumDataPoints()); if (parallel){ intStream = intStream.parallel(); } return intStream.mapToDouble(i -> predict(dataSet.getRow(i))).toArray(); }
Example #29
Source File: CTAT.java From pyramid with Apache License 2.0 | 5 votes |
/** * Find confidence threshold for target accuracy on validation dataset * @param confidence prediction confidence value for each instance in validation set * @param correctness correctness (true/false) of the prediction for each instance in validation set * @param targetAccuracy target accuracy level * @return summary that contains threshold, and various * auto-coding performance metrics on the validation set such as auto-coding percentage, auto-coding accuracy, * number of automated instances, number of correctly automated instances */ public static Summary findThreshold(double[] confidence, boolean[] correctness, double targetAccuracy){ if (confidence.length!=correctness.length){ throw new IllegalArgumentException("confidence.length!=correctness.length"); } Stream<Pair<Double, Double>> stream = IntStream.range(0, confidence.length).mapToObj(i->{ Pair<Double,Double> pair = new Pair<>(confidence[i],0.0); if (correctness[i]){ pair.setSecond(1.0); } return pair; }); return findThreshold(stream, targetAccuracy); }
Example #30
Source File: WhileOpTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test(groups = { "serialization-hostile" }) public void testIntDefaultClose() { AtomicBoolean isClosed = new AtomicBoolean(); IntStream s = IntStream.of(1, 2, 3).onClose(() -> isClosed.set(true)); try (IntStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { ds.count(); } assertTrue(isClosed.get()); }