英文:
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<String, Object> resultMap = new HashMap<>();
reasons.stream().forEach(reason -> {
if(reason.isNotChargable()) {
resultMap.put("reason1", reason);
} else {
resultMap.put("reason2", 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<String, Reason> results = reasons.stream()
.collect(Collectors.toMap(r -> r.isNotChargable() ? "reason1" : "reason2", Function.identity(), (existing, next) -> 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() ? "reason1" : "reason2", 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() ? "reason1" : "reason2";
resultMap.put(key , reason);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论