Java streams 7. Create using Stream.generate()

String get(){
return "x";
}
class SupplierImpl implements Supplier<String>{
public String get(){
return "x";
}
}
Stream<String> streamX = Stream.generate(new SupplierImpl());
streamX.limit(5).forEach(System.out::print); //prints: xxxxx
Stream<String> streamX2 = Stream.generate(() -> "x");
streamX2.limit(5).forEach(System.out::print); //prints: xxxxx
Stream<Integer> stream = Stream.generate(new Random()::nextInt);
stream.limit(2)
.map(i -> i.toString() + " ")
.forEach(System.out::print); //prints: -1097315144 1639784147
Stream.generate(new Random()::nextInt)
.limit(2)
.map(i -> i.toString() + " ")
.forEach(System.out::print); //prints: -288126400 -872136567
class SupplierImpl2 implements Supplier<String>{
private static int count = 1;
public String get(){
return String.valueOf(count++);
}
}
Stream.generate(new SupplierImpl2()::get)
.limit(5)
.forEach(System.out::print); //prints: 12345
class DemoClass {
private static int count = 1;
public String calculateString(){
return String.valueOf(count++);
}
}
Stream.generate(new DemoClass()::calculateString)
.limit(5)
.forEach(System.out::print); //prints: 12345
class DemoClass2 {
private static int count = 1;
public static String calculateString(){
return String.valueOf(count++);
}
}
Stream.generate(DemoClass2::calculateString)
.limit(5)
.forEach(System.out::print); //prints: 12345
import java.util.stream.Stream;

public class S07_CreateUsingGenerate2 {
private static int count = 1;

private static String calculateString(){
return String.valueOf(count++);
}

public static void main(String... args){
Stream.generate(() -> calculateString())
.limit(5)
.forEach(System.out::print); //prints: 12345
}
}
import java.util.stream.Stream;

public class S07_CreateUsingGenerate3 {
private int count2;

public String calcString(){
return String.valueOf(count2++);
}

public static void main(String... args){
Stream.generate(new S07_CreateUsingGenerate3()::calcString)
.limit(5)
.forEach(System.out::print); //prints: 12345
}
}
import java.util.stream.Stream;

public class S07_CreateUsingGenerate4 {
private int count2;

public String calculateString(){
return String.valueOf(count2++);
}

public static void main(String... args){
new S07_CreateUsingGenerate4().demo();
}

public void demo(){
Stream.generate(this::calculateString)
.limit(5)
.forEach(System.out::print); //prints: 12345

}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nick Samoylov

Nick Samoylov

Born in Moscow, lived in Crimea, now lives in the US. Used to be physicist and rock climber, now programmer and writer.