I am new to Java and its stream capabilities. How can this loop functionality be achieved with stream instead of the loop:
List<PackageData> packages = new ArrayList<>();
for(int i = 0; i < 100; i++) {
PackageData packageData = ImmutablePackageData.builder()
.withPackageGroup("ConstantString")
.withPackageType("ConstantString")
.withTrackingId("ConstantString" + i.toString())
.withLocationId("ConstantString" + i.toString())
.build();
packages.add(packageData);
}
You can utilize IntStream;
List<PackageData> packages = IntStream.range(0, 100)
.mapToObj(i -> ImmutablePackageData.builder()
.withPackageGroup("ConstantString")
.withPackageType("ConstantString")
.withTrackingId("ConstantString" + i)
.withLocationId("ConstantString" + i)
.build())
.collect(Collectors.toList())
Since your stream depends on nothing but a range of integer [0, 100)
check IntStream#range, and IntStream#mapToObj
From jdk-9 you can also use stream.iterate() to generate sequential stream
static <T> Stream<T> iterate(T seed,
Predicate<? super T> hasNext,
UnaryOperator<T> next)
Example
List<PackageData> packages = Stream.iterate(0, i->i<100, i->i+1)
.map(i-> -> ImmutablePackageData.builder()
.withPackageGroup("ConstantString")
.withPackageType("ConstantString")
.withTrackingId("ConstantString" + i)
.withLocationId("ConstantString" + i)
.build())
.collect(Collectors.toList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With