Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream map create objects with counter

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);
}
like image 993
Romonov Avatar asked Apr 24 '26 01:04

Romonov


2 Answers

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

like image 57
buræquete Avatar answered Apr 26 '26 14:04

buræquete


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())   
like image 41
Deadpool Avatar answered Apr 26 '26 14:04

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!