替换forEach语句下的if条件。

huangapple go评论46阅读模式
英文:

Replace if condition under forEach statement

问题

我想用三元运算符替换if条件。

Map<String, Object> resultMap = new HashMap<>();
reasons.stream().forEach(reason -> {
    resultMap.put(reason.isNotChargable() ? "reason1" : "reason2", reason);
});

其中reasons是一个列表对象。

英文:

I want to replace if condition with ternary operator.

Map&lt;String, Object&gt; resultMap = new HashMap&lt;&gt;();	
reasons.stream().forEach(reason -&gt; {					
	if(reason.isNotChargable()) {
		resultMap.put(&quot;reason1&quot;, reason);
	} else {
		resultMap.put(&quot;reason2&quot;, reason);
	}
});

Where reasons is a list object.

答案1

得分: 1

在for-each内部的更好选择是简单地从Stream创建一个Map,同时使用三元运算符确定键。我假设对象是Reason,因为它没有在问题中包含。

感谢@Naman,允许处理在收集多个相等的键时出现冲突。这将假定现有值而不是抛出IllegalStateException。

Map<String, Reason> results = reasons.stream()
        .collect(Collectors.toMap(r -> r.isNotChargable() ? "reason1" : "reason2", Function.identity(), (existing, next) -> existing);
英文:

A better alternative to ternary inside the for-each would be to simply create a Map from the Stream but also use ternary to determine key. I assume the object is Reason as it's not been included in question.

Props to @Naman for allowing this to handle conflicts when collecting multiple keys that are equal. This will assume the existing value instead of throwing an IllegalStateException.

Map&lt;String, Reason&gt; results = reasons.stream()
        .collect(Collectors.toMap(r -&gt; r.isNotChargable() ? &quot;reason1&quot; : &quot;reason2&quot;, Function.identity(), (existing, next) -&gt; existing);

答案2

得分: 0

用循环替换这部分。没有任何理由使用 forEach

for (ReasonType reason : reasons) {
  resultMap.put(reason.isNotChargeable() ? "reason1" : "reason2", reason);
}

(但是,你可以将这个 resultMap.put 放入一个 forEach 中;只是没有必要)。

英文:

Replace this with a loop. No reason at all to use forEach.

for (ReasonType reason : reasons) {
  resultMap.put(reason.isNotChargeable() ? &quot;reason1&quot; : &quot;reason2&quot;, reason);
}

(However, you can put this resultMap.put into a forEach; it's just unnecessary).

答案3

得分: 0

你可以尝试这样写:

String key = reason.isNotChargable() ? "reason1" : "reason2";
resultMap.put(key, reason);
英文:

You can try this :

String key = reason.isNotChargable() ? &quot;reason1&quot; : &quot;reason2&quot;;
resultMap.put(key , reason);

huangapple
  • 本文由 发表于 2020年7月22日 21:56:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63035916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定