public void testLongSize() { assertSized(LongStream.concat( LongStream.range(0, Long.MAX_VALUE / 2), LongStream.range(0, Long.MAX_VALUE / 2))); assertUnsized(LongStream.concat( LongStream.range(0, Long.MAX_VALUE), LongStream.range(0, Long.MAX_VALUE))); assertUnsized(LongStream.concat( LongStream.range(0, Long.MAX_VALUE), LongStream.iterate(0, i -> i + 1))); assertUnsized(LongStream.concat( LongStream.iterate(0, i -> i + 1), LongStream.range(0, Long.MAX_VALUE))); }
private void testDropWhileMulti(Consumer<Stream<Integer>> mRef, Consumer<IntStream> mInt, Consumer<LongStream> mLong, Consumer<DoubleStream> mDouble) { Map<String, Supplier<Stream<Integer>>> sources = new HashMap<>(); sources.put("IntStream.range().boxed()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed()); sources.put("IntStream.range().boxed().unordered()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed().unordered()); sources.put("LinkedList.stream()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() .collect(toCollection(LinkedList::new)) .stream()); sources.put("LinkedList.stream().unordered()", () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() .collect(toCollection(LinkedList::new)) .stream() .unordered()); testWhileMulti(sources, mRef, mInt, mLong, mDouble); }
@Override public TimeGraphStateRender getStateRender(TimeGraphTreeElement treeElement, TimeRange timeRange, long resolution, FutureTask<?> task) { int entryIndex = Integer.valueOf(treeElement.getName().substring(TestModelProvider.ENTRY_NAME_PREFIX.length())); long stateLength = entryIndex * DURATION_FACTOR; List<TimeGraphStateInterval> intervals = LongStream.iterate(timeRange.getStartTime(), i -> i + stateLength) .limit((timeRange.getDuration() / stateLength) + 1) .mapToObj(startTime -> { long endTime = startTime + stateLength - 1; StateDefinition stateDef = getNextStateDef(); return new BasicTimeGraphStateInterval(startTime, endTime, treeElement, stateDef, stateDef.getName(), Collections.emptyMap()); }) .collect(Collectors.toList()); return new TimeGraphStateRender(timeRange, treeElement, intervals); }
@Test public void buildDateList() { LocalDate today = LocalDate.now() ; logger.info( "now: {} ", today.format(DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) ); List<String> past10days= LongStream .rangeClosed(1, 10) .mapToObj( day -> today.minusDays( day ) ) .map( offsetDate -> offsetDate.format(DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) ) .collect( Collectors.toList() ); List<String> past10daysReverse = LongStream.iterate(10, e -> e - 1) .limit(10) .mapToObj( day -> today.minusDays( day ) ) .map( offsetDate -> offsetDate.format(DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) ) .collect( Collectors.toList() ); logger.info( "past10days: {} \n reverse: {}", past10days, past10daysReverse ); }
@Test public void LongPredicate() { // TODO - Convert the anonymous inner class to a lambda LongPredicate predicate = new LongPredicate() { @Override public boolean test(long value) { return value % 2 == 0; } }; List<Long> evens = LongStream.rangeClosed(1, 5).filter(predicate).boxed().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(2L, 4L), evens); List<Long> odds = LongStream.rangeClosed(1, 5).filter(predicate.negate()).boxed().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(1L, 3L, 5L), odds); Assert.assertTrue(LongStream.rangeClosed(1, 5).anyMatch(predicate)); Assert.assertFalse(LongStream.rangeClosed(1, 5).allMatch(predicate)); Assert.assertFalse(LongStream.rangeClosed(1, 5).noneMatch(predicate)); }
private void testWhileMulti(TestData.OfRef<Integer> data, ResultAsserter<Iterable<Integer>> ra, Function<Stream<Integer>, Stream<Integer>> mRef, Function<IntStream, IntStream> mInt, Function<LongStream, LongStream> mLong, Function<DoubleStream, DoubleStream> mDouble) { Map<String, Function<Stream<Integer>, Stream<Integer>>> ms = new HashMap<>(); ms.put("Ref", mRef); ms.put("Int", s -> mInt.apply(s.mapToInt(e -> e)).mapToObj(e -> e)); ms.put("Long", s -> mLong.apply(s.mapToLong(e -> e)).mapToObj(e -> (int) e)); ms.put("Double", s -> mDouble.apply(s.mapToDouble(e -> e)).mapToObj(e -> (int) e)); ms.put("Ref using defaults", s -> mRef.apply(DefaultMethodStreams.delegateTo(s))); ms.put("Int using defaults", s -> mInt.apply(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e))).mapToObj(e -> e)); ms.put("Long using defaults", s -> mLong.apply(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e))).mapToObj(e -> (int) e)); ms.put("Double using defaults", s -> mDouble.apply(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e))).mapToObj(e -> (int) e)); testWhileMulti(data, ra, ms); }
public void testSize() { assertSized(Stream.concat( LongStream.range(0, Long.MAX_VALUE / 2).boxed(), LongStream.range(0, Long.MAX_VALUE / 2).boxed())); assertUnsized(Stream.concat( LongStream.range(0, Long.MAX_VALUE).boxed(), LongStream.range(0, Long.MAX_VALUE).boxed())); assertUnsized(Stream.concat( LongStream.range(0, Long.MAX_VALUE).boxed(), Stream.iterate(0, i -> i + 1))); assertUnsized(Stream.concat( Stream.iterate(0, i -> i + 1), LongStream.range(0, Long.MAX_VALUE).boxed())); }
private static void produceRecords(String bootstrapServers) { Properties properties = new Properties(); properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); Producer<Long, byte[]> producer = new KafkaProducer<>(properties); LongStream.rangeClosed(1, 100).boxed() .map(number -> new ProducerRecord<>( TOPIC, //topic number, //key String.format("record-%s", number.toString()).getBytes())) //value .forEach(record -> producer.send(record)); producer.close(); }
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class) public void testOps(String name, TestData.OfRef<Integer> data) { exerciseOpsInt(data, s -> Stream.concat(s, data.stream()), s -> IntStream.concat(s, data.stream().mapToInt(Integer::intValue)), s -> LongStream.concat(s, data.stream().mapToLong(Integer::longValue)), s -> DoubleStream.concat(s, data.stream().mapToDouble(Integer::doubleValue))); }
@Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class) public void testLongOps(String name, TestData.OfLong data) { Collection<Long> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToLong(j -> j))); assertEquals(data.size(), result.size()); assertContents(data, result); result = exerciseOps(data, s -> LongStream.empty()); assertEquals(0, result.size()); }
@DataProvider(name = "LongStream.limit") public static Object[][] longSliceFunctionsDataProvider() { Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE); List<Object[]> data = new ArrayList<>(); data.add(new Object[]{f.apply("LongStream.limit(%d)"), (UnaryOperator<LongStream>) s -> s.limit(SKIP_LIMIT_SIZE)}); data.add(new Object[]{f.apply("LongStream.skip(%1$d).limit(%1$d)"), (UnaryOperator<LongStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); return data.toArray(new Object[0][]); }
public void testDoubleStreamMatches() { assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, false, false, false, false); assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, true, true, true); assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, true, true, true, true); assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, true, false, false, true); assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, true); assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, false, true, true, false); assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, true, false, true, true); assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, false); assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, false, true, false, false); }
public void testFindLast_longStream() { Truth.assertThat(findLast(LongStream.of())).isEqualTo(OptionalLong.empty()); Truth.assertThat(findLast(LongStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalLong.of(5)); // test with a large, not-subsized Spliterator List<Long> list = LongStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new)); Truth.assertThat(findLast(list.stream().mapToLong(i -> i))).isEqualTo(OptionalLong.of(10000)); // no way to find out the stream is empty without walking its spliterator Truth.assertThat(findLast(list.stream().mapToLong(i -> i).filter(i -> i < 0))) .isEqualTo(OptionalLong.empty()); }
@Test public void testLongSingleton() { TestData.OfLong data = TestData.Factory.ofLongSupplier("[0, 1)", () -> LongStream.of(1)); withData(data). stream(s -> s). expectedResult(Collections.singletonList(1L)). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(Collections.singletonList(1L)). exercise(); }
@Test @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void testManageTempList() { final List<Long> values = LongStream.range(0L, TEMP_LIST_CAPACITY) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); final Long listId = daoHelper.createTempLongList(0L, values); assertNotNull("The temporary list ID cannot be null.", listId); assertEquals("Unexpected capacity of a temporary list.", TEMP_LIST_CAPACITY, new Long(daoHelper.clearTempList(listId))); // make sure that previously created values has been cleared daoHelper.createTempLongList(0L, values); assertEquals("Unexpected capacity of a temporary list.", TEMP_LIST_CAPACITY, new Long(daoHelper.clearTempList(listId))); }
public void testLongCollectNull() { checkNPE(() -> LongStream.of(1).collect(null, LongSummaryStatistics::accept, LongSummaryStatistics::combine)); checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new, null, LongSummaryStatistics::combine)); checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new, LongSummaryStatistics::accept, null)); }
public static Object arrayToStream(final Object array) { if (array instanceof int[]) { return IntStream.of((int[])array); } else if (array instanceof long[]) { return LongStream.of((long[])array); } else if (array instanceof double[]) { return DoubleStream.of((double[])array); } else if (array instanceof Object[]) { return Stream.of((Object[])array); } else { throw new IllegalArgumentException(); } }
private void testSliceMulti(TestData.OfRef<Integer> data, int expectedSize, Function<Stream<Integer>, Stream<Integer>> mRef, Function<IntStream, IntStream> mInt, Function<LongStream, LongStream> mLong, Function<DoubleStream, DoubleStream> mDouble) { @SuppressWarnings({ "rawtypes", "unchecked" }) Function<Stream<Integer>, Stream<Integer>>[] ms = new Function[4]; ms[0] = mRef; ms[1] = s -> mInt.apply(s.mapToInt(e -> e)).mapToObj(e -> e); ms[2] = s -> mLong.apply(s.mapToLong(e -> e)).mapToObj(e -> (int) e); ms[3] = s -> mDouble.apply(s.mapToDouble(e -> e)).mapToObj(e -> (int) e); testSliceMulti(data, expectedSize, ms); }
private ActorRef storage(String prefix) { final Set<ActorPath> storagePaths = LongStream.range(0, PRIEST_COUNT) .boxed() .map(l -> system.child(prefix + l)) .collect(toSet()); final List<ActorRef> testPriests = LongStream.range(0, PRIEST_COUNT) .boxed() .map(l -> system.actorOf(LinearizableStorage.props(new Cluster(storagePaths)), prefix + l)) .collect(toList()); return testPriests.get(0); }
@Test public void testPaging() { Page<User> userPage = pagingUserInterface.findAll(new PageRequest(0, 5)); List<User> users = userPage.getContent(); Assert.assertThat(users, hasSize(5)); Assert.assertThat( users.stream().map(it -> it.id).collect(Collectors.toList()), contains(LongStream.rangeClosed(1, 5).boxed().toArray(Long[]::new)) ); }
@Test public void testPagingAndSortById() { Page<User> userPage = pagingUserInterface.findAll( new PageRequest(0, 5, new Sort(Sort.Direction.DESC, "id")) ); List<User> users = userPage.getContent(); Assert.assertThat( users.stream().map(it -> it.id).collect(Collectors.toList()), contains(LongStream.iterate(10, i -> i - 1).limit(5).boxed().toArray(Long[]::new)) ); }
@Test(groups = { "serialization-hostile" }) public void testLongDefaultClose() { AtomicBoolean isClosed = new AtomicBoolean(); LongStream s = LongStream.of(1, 2, 3).onClose(() -> isClosed.set(true)); try (LongStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { ds.count(); } assertTrue(isClosed.get()); }
public static void main(String[] args) throws InterruptedException { SubmissionPublisher<Long> publisher = new SubmissionPublisher(); int count = 5; WelcomeSubscriber subscriber = new WelcomeSubscriber(count); publisher.subscribe(subscriber); LongStream.range(10, 20).forEach(publisher::submit); Thread.sleep(1000); }
private void assertLongPredicates(Supplier<LongStream> source, Kind kind, LongPredicate[] predicates, boolean... answers) { for (int i = 0; i < predicates.length; i++) { setContext("i", i); boolean match = longKinds.get(kind).apply(predicates[i]).apply(source.get()); assertEquals(answers[i], match, kind.toString() + predicates[i].toString()); } }
public static void publish()throws InterruptedException, ExecutionException { CompletableFuture future = null; try (SubmissionPublisher publisher = new SubmissionPublisher<Long>()) { System.out.println("Subscriber Buffer Size: " + publisher.getMaxBufferCapacity()); future=publisher.consume(System.out::println); LongStream.range(10, 20).forEach(publisher::submit); } finally { future.get(); } }
@Test(dataProvider = "LongStream.limit") public void testLongSubsizedWithRange(String description, UnaryOperator<LongStream> fs) { // Range is [0, Long.MAX_VALUE), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations withData(longs()). stream(s -> fs.apply(s)). without(LongStreamTestScenario.CLEAR_SIZED_SCENARIOS). exercise(); }
@Test public void testLongSingleton() { TestData.OfLong data = TestData.Factory.ofLongSupplier("{1}", () -> LongStream.of(1)); withData(data). stream(s -> s). expectedResult(Collections.singletonList(1L)). exercise(); withData(data). stream(s -> s.map(i -> i)). expectedResult(Collections.singletonList(1L)). exercise(); }
@Test(dataProvider = TEST) public void testCommit( List<List<Object>> changes, long deadTransaction, List<Integer> expectedCommitted, List<Map.Entry<Integer, Integer>> expectedBefore ) { ByteBuffer buffer = ByteBuffer.allocate(0); List<Long> txIdsToCommit = LongStream.range(0, changes.size()).boxed().collect(toList()); Map<Long, TransactionData> input = new HashMap<>(changes.size()); for (int i = 0; i < changes.size(); i++) { List<Map.Entry<String, List>> list = singletonList(pair(CACHE_NAME, changes.get(i))); TransactionData data = new TransactionData(new TransactionScope((long) i, list), buffer, new TopicPartition("topic", 0), 0L); input.put((long) i, data); } CommitServitor servitor = mock(CommitServitor.class); List<Long> actual = Collections.synchronizedList(new ArrayList<>()); doAnswer(mock -> !mock.getArguments()[0].equals(deadTransaction) && actual.add((Long) mock.getArguments()[0])) .when(servitor) .commit(anyLong(), anyMap()); ParallelCommitStrategy strategy = new ParallelCommitStrategy(servitor, "localGridName"); List<Long> actualCommitted = strategy.commit(txIdsToCommit, input); Assert.assertEquals(actualCommitted, expectedCommitted.stream().map(Integer::longValue).collect(toList())); checkOrder(expectedBefore, actual); }
public void testLongStreamMatches() { assertLongPredicates(() -> LongStream.range(0, 0), Kind.ANY, LONG_PREDICATES, false, false, false, false); assertLongPredicates(() -> LongStream.range(0, 0), Kind.ALL, LONG_PREDICATES, true, true, true, true); assertLongPredicates(() -> LongStream.range(0, 0), Kind.NONE, LONG_PREDICATES, true, true, true, true); assertLongPredicates(() -> LongStream.range(1, 2), Kind.ANY, LONG_PREDICATES, true, false, false, true); assertLongPredicates(() -> LongStream.range(1, 2), Kind.ALL, LONG_PREDICATES, true, false, false, true); assertLongPredicates(() -> LongStream.range(1, 2), Kind.NONE, LONG_PREDICATES, false, true, true, false); assertLongPredicates(() -> LongStream.range(1, 6), Kind.ANY, LONG_PREDICATES, true, false, true, true); assertLongPredicates(() -> LongStream.range(1, 6), Kind.ALL, LONG_PREDICATES, true, false, false, false); assertLongPredicates(() -> LongStream.range(1, 6), Kind.NONE, LONG_PREDICATES, false, true, false, false); }
@Test(dataProvider = "LongStream.limit") public void testLongUnorderedSizedNotSubsizedFinite(String description, UnaryOperator<LongStream> fs) { // Range is [0, Long.MAX_VALUE), splits are not SUBSIZED (proxy clears // the SUBSIZED characteristic) // Such a size will induce out of memory errors for incorrect // slice implementations withData(proxiedLongRange(0, Long.MAX_VALUE)). stream(s -> fs.apply(s.unordered())). resultAsserter(unorderedAsserter()). exercise(); }
/** * Random类提供的随机数字流 */ @Test public void testRandomStream() { IntStream intStream = new Random().ints(); DoubleStream doubleStream = new Random().doubles(); LongStream longStream = new Random().longs(); /** * ints(long streamSize, int randomNumberOrigin,int randomNumberBound) * 10 表示这个流有几个数据 * 20,100 是生成的数据的范围 */ IntStream stream = new Random().ints(10, 20, 100); stream.forEach(System.out::println); }
private void testTakeWhileMulti(Consumer<Stream<Integer>> mRef, Consumer<IntStream> mInt, Consumer<LongStream> mLong, Consumer<DoubleStream> mDouble) { Map<String, Supplier<Stream<Integer>>> sources = new HashMap<>(); sources.put("Stream.generate()", () -> Stream.generate(() -> 1)); sources.put("Stream.iterate()", () -> Stream.iterate(1, x -> 1)); sources.put("Stream.iterate().unordered()", () -> Stream.iterate(1, x -> 1)); testWhileMulti(sources, mRef, mInt, mLong, mDouble); }
public void testConcat_longStream() { assertThat( Streams.concat( LongStream.of(1), LongStream.of(2), LongStream.empty(), LongStream.of(3, 4))) .containsExactly(1L, 2L, 3L, 4L) .inOrder(); }
public void testBox() { List<Long> l = LongStream.range(1, 10).parallel().boxed().collect(Collectors.toList()); long sum = l.stream().reduce(0L, (a, b) -> a + b); assertEquals(sum, 45); }
private Observable<Long> countStreamForTickFetch(final long endTime) { final LongStream counter = LongStream .iterate(1, i -> i + 1) .map(count -> endTime - count * tickFetchMillis + 1); return Observable.fromIterable(counter::iterator); }
/** * @return The total amount of nanoseconds that all passes took */ public final long getTotal() { return LongStream.of(results).sum(); }
public void testSum() { long sum = LongStream.range(1, 10).filter(i -> i % 2 == 0).sum(); assertEquals(sum, 20); }