Java流图使用计数器创建对象

时间:2019-07-16 00:35:00

标签: java java-stream

我不熟悉Java及其流功能。如何使用流而不是循环来实现此循环功能:

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

3 个答案:

答案 0 :(得分:4)

您可以利用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())

由于您的流只依赖于整数[0, 100)的范围

选中IntStream#rangeIntStream#mapToObj

答案 1 :(得分:4)

在jdk-9中,您还可以使用stream.iterate()生成顺序流

static <T> Stream<T> iterate​(T seed,
                         Predicate<? super T> hasNext,
                         UnaryOperator<T> next)

示例

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

答案 2 :(得分:1)

我会使用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());