简体   繁体   中英

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);
}

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())   

I'd use Stream.iterate

List<PackageData> packages = Stream.iterate(0, (index) -> ImmutablePackageData.builder()
    .withPackageGroup("ConstantString")
    .withPackageType("ConstantString")
    .withTrackingId("ConstantString" + index)
    .withLocationId("ConstantString" + index)
    .build())
.limit(100)
.collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM