我有一个要迭代的映射,我想用两个条件检查entryset的值:如果满足条件1,则将其分组为一个集合public class UserData
{
public string Conditions { get; set; }
public DateTime Status { get; set; }
public Dictionary<string, Guid> userSelections { get; set; } = new Dictionary<string, Guid>();
}
并得到0: Name: "Pete", Status: "open", id="af9f9937-f51a-4fd8-b29c-f9ef899684c9"
1: Name: "Smith", Status: "closed", id="vfdf9337-f51s-wfd8-b49-f5ef799h84c9"
2: Name: "Ang", Status: "open", id="334dd33-d3e3-cxc333-e3c-ccdc3cd32"
,如果不满足,则使用另一个条件进行过滤并收集到另一个集合中,执行相同的操作。
我在一次迭代中使用了//this holds above data
const userSelectedData = [];
const userData = {
'name': userName,
'conditions': conditions,
'userSelections': userSelectedData
};
this.service.save(userData)
.subscribe(
(res) => {
//saved
});
}
循环。现在,如果我只想对Java 8流进行一次迭代,可以吗?
我尝试过var sand = document.getElementById('tim-sand')
var Sel = {
timSand: sand,
timSandHei: getComputedStyle(sand).height, //Working
}
(重复两次)。
我还检查了findFirst()
和Optional<>
,但还没有看到这种可能性。
方法1的示例:
for
方法2的示例:
stream().filter(cond1).map(Map.Entry::getValue).findFirst()
答案 0 :(得分:2)
如果您的条件仅基于.equals()
的键和值,就像您在问题中所显示的那样,则可以使用map.get()
和简单的if
语句:>
Response result = responses.get("foo");
if (result == null || result.equals(bar))
result = responses.get("some other key");
因此不需要使用其他任何东西。
或者按照Holger的建议,您也可以使用map.getOrDefault()
:
Response result = responses.getOrDefault("foo", bar);
if(result.equals(bar))
result = responses.get("some other key");
答案 1 :(得分:1)
这可能是您使用Optional
所需要的:
Response response = Optional
.ofNullable(responses.get("foo")) // find the "foo" Response
.filter(value -> !"bar".equals(value)) // except if is null or "bar"
.orElse(responses.get("other")); // then find the "other" response (then null)
很少有见解:
具有代码:
if (key.equals("foo") && !value.equals("bar")) {
res1 = value;
} else if (key.equals("some other key")) {
res2 = value;
}
在循环内部,每次循环都不必要地检查两个条件,尽管每个键只能出现一次。如果设置了break
和res1
,请考虑使用res2
。
entry.getKey().equals("foo")
应当缩短为map.get("foo")
,如果不存在密钥,它将返回null
。这就是为什么我将此行为与Optional
一起使用的原因。