Java stream map create objects with counter

Romonov :

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);
}
buræquete :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127231&siteId=1