Java8流:在流中使用if/else条件

Java8流:在流中使用if/else条件,java,java-8,java-stream,Java,Java 8,Java Stream,我已经使用Java8流有一段时间了。我遇到了一种情况,在迭代流时需要使用if/else条件。我有一张这样的清单。我想为列表中的每个项目创建MetricForAccount类的对象 private List<String> metricNames = ImmutableList.of("ReadConsumedCapacity", "WriteConsumedCapacity", "SuccessfulReque

我已经使用Java8流有一段时间了。我遇到了一种情况,在迭代流时需要使用if/else条件。我有一张这样的清单。我想为列表中的每个项目创建MetricForAccount类的对象

private List<String> metricNames = ImmutableList.of("ReadConsumedCapacity",
            "WriteConsumedCapacity", "SuccessfulRequestLatency", "ReturnedItemCount");

我想根据度量名称向维度列表添加不同的项。我不知道如何使用地图中的if-else。有什么建议吗?

您可以简单地扩展回调,并在此回调中使用and if/else语句。 像这样:

列表维度=新的ArrayList; metricNames.stream .mapmetricName->{ 如果匹配MetricName,则返回Account.withAccountIdsubscriberId的新MetricForAccount .WithMetricName MetricName .带statsum .带周期 .使用名称空间AWS\u DYNAMO\u DB\u名称空间 .WithRegion区域 .带有尺寸标注 .范围内; 否则返回Account.withAccountIdsubscriberId的新MetricForAccount .WithMetricName MetricName .带statsum .带周期 .使用名称空间AWS\u DYNAMO\u DB\u名称空间 .WithRegion区域 .具有多个尺寸 .范围内; } .toList;
如果你写lambda metricName->{…},那么你可以在正文中放入任意多行普通源代码。可能我的问题不清楚。我想在维度列表中添加不同的项,.withDimensionsdimensions。。休息吧,一切都会好起来的same@LouisWasserman我明白你的意思。我想要一个优化的方法来改变上述情况下的维度列表,你知道在不涉及流的情况下如何做吗?可能是我的问题不清楚。我想在维度列表中添加不同的项,.withDimensionsdimensions。。剩下的一切都会是sameYes我不理解你的意思,或者至少我认为我理解了,我编辑了我的答案,请看一下。如果是这样的话,为什么不使用三元运算符作为Account.withAccountIdsubscriberId.withMetricNamemetricName.withStatSUM.withPeriodPERIOD.withNamespaceAWS\U DYNAMO\U DB\U NAMESPACE.withRegionregion.withDimensionsmatchesmetricName的返回新度量值?尺寸:其他尺寸。带范围;
List<Dimension> dimensions = new ArrayList<>();


metricNames.stream()
                .map(metricName -> new MetricForAccount().withAccountId(subscriberId)
                        .withMetricName(metricName)
                        .withStat(SUM)
                        .withPeriod(PERIOD)
                        .withNamespace(AWS_DYNAMO_DB_NAMESPACE)
                        .withRegion(region)
                        .withDimensions(dimensions)
                        .withRange(range))
                .collect(Collectors.toList());