本文整理了Java中java.util.stream.Stream.iterate()
方法的一些代码示例,展示了Stream.iterate()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.iterate()
方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:iterate
暂无
canonical example by Tabnine
public List<Integer> findDivisors(int number) {
return Stream.iterate(1, k -> ++k)
.limit(number)
.filter(k -> number % k == 0)
.collect(Collectors.toList());
}
canonical example by Tabnine
public void printFibonacciSequence(int length) {
System.out.println(
Stream.iterate(new long[] {0, 1}, pair -> new long[] {pair[1], pair[0] + pair[1]})
.limit(length)
.map(pair -> Long.toString(pair[1]))
.collect(Collectors.joining(", ")));
}
代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises
static void iterate() {
Stream.iterate(0, x -> x + 1)
.limit(5)
.forEach(System.out::println);
}
代码示例来源:origin: google/guava
public void testZipInfiniteWithInfinite() {
// zip is doing an infinite zip, but we truncate the result so we can actually test it
// but we want the zip itself to work
assertThat(
Streams.zip(
Stream.iterate(1, i -> i + 1).map(String::valueOf),
Stream.iterate(1, i -> i + 1),
(String str, Integer i) -> str.equals(Integer.toString(i)))
.limit(100))
.doesNotContain(false);
}
代码示例来源:origin: google/guava
public void testForEachPair_finiteWithInfinite() {
List<String> list = new ArrayList<>();
Streams.forEachPair(
Stream.of("a", "b", "c"), Stream.iterate(1, i -> i + 1), (a, b) -> list.add(a + ":" + b));
Truth.assertThat(list).containsExactly("a:1", "b:2", "c:3");
}
代码示例来源:origin: Vedenin/useful-java-links
Stream<Integer> streamFromIterate = Stream.iterate(1, n -> n + 2);
System.out.println("streamFromIterate = " + streamFromIterate.limit(3).collect(Collectors.toList())); // print streamFromIterate = [1, 3, 5]
代码示例来源:origin: google/guava
public void testZipFiniteWithInfinite() {
assertThat(
Streams.zip(
Stream.of("a", "b", "c"), Stream.iterate(1, i -> i + 1), (a, b) -> a + ":" + b))
.containsExactly("a:1", "b:2", "c:3")
.inOrder();
}
代码示例来源:origin: google/error-prone
private Description matchNewClassOrMethodInvocation(
MethodSymbol symbol, ImmutableList<Commented<ExpressionTree>> arguments, Tree tree) {
if (symbol.getParameters().isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
forEachPair(
arguments.stream(),
Stream.concat(
symbol.getParameters().stream(),
Stream.iterate(getLast(symbol.getParameters()), x -> x)),
(commented, param) -> {
ImmutableList<Comment> comments =
commented.afterComments().isEmpty()
? commented.beforeComments()
: commented.afterComments();
boolean matchStandardForm = !commented.afterComments().isEmpty();
comments.stream()
.filter(c -> matchingParamComment(c, param, matchStandardForm))
.findFirst()
.ifPresent(c -> fixParamComment(fix, commented, param, c));
});
return fix.isEmpty() ? NO_MATCH : describeMatch(tree, fix.build());
}
代码示例来源:origin: apache/incubator-gobblin
@Test
public void test() {
RowLevelPolicyChecker.FrontLoadedSampler sampler =
new RowLevelPolicyChecker.FrontLoadedSampler(10, 2);
List<Integer> sampled = Stream.iterate(0, i -> i++).limit(1000).filter(i -> sampler.acceptNext()).collect(Collectors.toList());
Assert.assertTrue(sampled.size() >= 10);
Assert.assertTrue(sampled.size() < 30);
// check the first 10 values are the integers from 1 to 9
Assert.assertEquals(sampled.subList(0, 10), Stream.iterate(0, i -> i++).limit(10).collect(Collectors.toList()));
// with a very large decay factor, should have very few additional samples
RowLevelPolicyChecker.FrontLoadedSampler sampler2 =
new RowLevelPolicyChecker.FrontLoadedSampler(10, 10);
sampled = Stream.iterate(0, i -> i++).limit(1000).filter(i -> sampler2.acceptNext()).collect(Collectors.toList());
Assert.assertTrue(sampled.size() >= 10);
Assert.assertTrue(sampled.size() < 15);
// check the first 10 values are the integers from 1 to 9
Assert.assertEquals(sampled.subList(0, 10), Stream.iterate(0, i -> i++).limit(10).collect(Collectors.toList()));
// with a low decay factor, should have many additional samples
RowLevelPolicyChecker.FrontLoadedSampler sampler3 =
new RowLevelPolicyChecker.FrontLoadedSampler(10, 1.2);
sampled = Stream.iterate(0, i -> i++).limit(1000).filter(i -> sampler3.acceptNext()).collect(Collectors.toList());
Assert.assertTrue(sampled.size() >= 30);
Assert.assertTrue(sampled.size() < 100);
// check the first 10 values are the integers from 1 to 9
Assert.assertEquals(sampled.subList(0, 10), Stream.iterate(0, i -> i++).limit(10).collect(Collectors.toList()));
}
代码示例来源:origin: google/bundletool
private static ZipPath getUniqueResourcePath(ModuleSplit split) {
return Stream.iterate(0, i -> i + 1)
.map(number -> ZipPath.create(String.format(XML_PATH_PATTERN, number)))
.filter(path -> !split.findEntry(path).isPresent())
.findFirst()
.get();
}
}
代码示例来源:origin: biezhi/learn-java8
public static void main(String[] args) {
// tuple = (0, 1)
// next [0] = prev tuple [1]
// next [1] = prev (tuple [0] + tuple[1])
Stream.iterate(new Tuple(0, 1), tuple -> new Tuple(tuple.second, tuple.first + tuple.second))
.limit(20)
.forEach(tuple -> System.out.println("("+ tuple.first +","+ tuple.second +")"));
}
代码示例来源:origin: aol/cyclops
/**
* Create a Stream that infiniteable cycles the provided Streamable
* @param s Streamable to cycle
* @return New cycling stream
*/
public static <U> Stream<U> cycle(final Streamable<U> s) {
return Stream.iterate(s.stream(), s1 -> s.stream())
.flatMap(Function.identity());
}
代码示例来源:origin: aol/cyclops
/**
* Create a Stream that finitely cycles the provided Streamable, provided number of times
*
* <pre>
* {@code
* assertThat(StreamUtils.cycle(3,Streamable.of(1,2,2))
.collect(CyclopsCollectors.toList()),
equalTo(Arrays.asList(1,2,2,1,2,2,1,2,2)));
* }
* </pre>
* @param s Streamable to cycle
* @return New cycling stream
*/
public static <U> Stream<U> cycle(final int times, final Streamable<U> s) {
return Stream.iterate(s.stream(), s1 -> s.stream())
.limit(times)
.flatMap(Function.identity());
}
代码示例来源:origin: aol/cyclops
/**
* Create a Stream that finitely cycles the provided Streamable, provided number of times
*
* <pre>
* {@code
* assertThat(Streams.cycle(3,Streamable.of(1,2,2))
.collect(CyclopsCollectors.toList()),
equalTo(Arrays.asList(1,2,2,1,2,2,1,2,2)));
* }
* </pre>
* @param s Streamable to cycle
* @return New cycling stream
*/
public static <U> Stream<U> cycle(final long times, final Streamable<U> s) {
return Stream.iterate(s.stream(), s1 -> s.stream())
.limit(times)
.flatMap(Function.identity());
}
代码示例来源:origin: aol/cyclops
@Test
public void compareConcat(){
List<Integer> oneThousand= Stream.iterate(1,i->i+1).limit(1000).collect(Collectors.toList());
int total = 0;
for(int x=0;x<10;x++) {
total += Stream.concat(oneThousand.stream(),oneThousand.stream()).count();
}
long time = System.currentTimeMillis();
for(int k=0;k<5000;k++)
count += Stream.concat(oneThousand.stream(),oneThousand.stream()).count();
long stream = System.currentTimeMillis()-time;
for(int x=0;x<10;x++) {
total += ReactiveSeq.concat(oneThousand.stream(),oneThousand.stream()).count();
}
long time2 = System.currentTimeMillis();
for(int k=0;k<5000;k++)
count += ReactiveSeq.concat(oneThousand.stream(),oneThousand.stream()).count();
long rs = System.currentTimeMillis()-time2;
System.out.println("Stream " + stream + " rs with construction " + rs + " count " + count);
}
@Test
代码示例来源:origin: aol/cyclops
@Test
public void compareFlatMap(){
for(int k=0;k<10;k++)
count += Stream.generate(()->1).limit(100).flatMap(i->Stream.iterate(1,x->x+i).limit(500)).count();
long time = System.currentTimeMillis();
for(int k=0;k<1000;k++)
count += Stream.generate(()->1).limit(100).flatMap(i->Stream.iterate(1,x->x+i).limit(500)).count();
long stream = System.currentTimeMillis()-time;
for(int k=0;k<10;k++)
count += ReactiveSeq.generate(()->1).limit(100).flatMap(i->Stream.iterate(1,x->x+i).limit(500)).count();
long time2 = System.currentTimeMillis();
for(int k=0;k<1000;k++)
count += ReactiveSeq.generate(()->1).limit(100).flatMap(i->Stream.iterate(1,x->x+i).limit(500)).count();
long rs = System.currentTimeMillis()-time2;
System.out.println("Stream " + stream + " rs with construction " + rs + " count " + count);
}
@Test
代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures
@Test public void testOrderByDate() throws Exception {
SimpleDateFormat format = formatInUtcZone("yyyy-MM-dd HH:mm:ss");
try (Transaction tx = db.beginTx()) {
for (int i = 0 ; i < 8; i++) {
Node datedNode = db.createNode(() -> "Person");
datedNode.setProperty("born", format.format(java.util.Date.from(Instant.EPOCH.plus(i, ChronoUnit.DAYS))));
}
for (int i = 15 ; i >= 8; i--) {
Node datedNode = db.createNode(() -> "Person");
datedNode.setProperty("born", format.format(java.util.Date.from(Instant.EPOCH.plus(i, ChronoUnit.DAYS))));
}
tx.success();
}
List<java.util.Date> expected = Stream.iterate(Instant.EPOCH, prev -> prev.plus(1, ChronoUnit.DAYS))
.limit(16)
.map(java.util.Date::from)
.sorted()
.collect(toList());
List<java.util.Date> actual;
try (Transaction tx = db.beginTx()) {
String query = "MATCH (p:Person) RETURN p, apoc.date.parse(p.born,'s') as dob ORDER BY dob ";
actual = Iterators.asList(db.execute(query).<Long>columnAs("dob")).stream()
.map(dob -> java.util.Date.from(Instant.ofEpochSecond((long) dob)))
.collect(toList());
tx.success();
}
assertEquals(expected, actual);
}
代码示例来源:origin: aol/cyclops
Stream.iterate(1,i->i+1).limit(10000)
.map(i->i*100)
.map(i -> i * 2)
代码示例来源:origin: aol/cyclops
@Test
public void testIterate() {
assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(
Stream.iterate(just.get(),i->i+1).limit(10).mapToInt(i->i).sum()));
assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(145));
}
代码示例来源:origin: aol/cyclops
@Test
public void testIterate() {
assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(
Stream.iterate(just.get(),i->i+1).limit(10).mapToInt(i->i).sum()));
assertThat(just.asSupplier(-10000).iterate(i->i+1).limit(10).sumInt(i->i),equalTo(145));
}
内容来源于网络,如有侵权,请联系作者删除!