[英]Lambda expression in JAVA for Nested Conditions
我有以下Map
:
HashMap<String, String> map1= new HashMap<String, String>();
map1.put("1", "One");
map1.put("2", "Two");
map1.put("3", "Three");
我有一个包含["1","2","3"]
的列表numbers
我必须执行以下操作:
List<String> spelling= new ArrayList<>();
for (String num: numbers) {
if (map1.containsKey(num)){
spelling.add(map1.get(num))
}
}
如何使用lambda表达式编写上述代码?
使用Stream
:
List<String> spelling = numbers.stream()
.map(map1::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println (spelling);
请注意,我只是使用get
,而不是检查某个键是否在带有containsKey
的映射containsKey
,然后过滤掉了null
。
输出:
[One, Two, Three]
Eran解决方案的变体:
map1
包含null
值,则使用containsKey
而不是检查null
值=>检查null
值会产生错误的结果。 代码片段:
List<String> spelling = numbers.stream()
.filter(map1::containsKey)
.map(map1::get)
.collect(Collectors.toList());
System.out.println (spelling);
另一种选择是使用forEach
构造:
numbers.forEach(n -> {
if(map1.containsKey(n))
spelling.add(map1.get(n));
});
试试这样吧
List<String> spelling = map1.keySet().stream()
.filter(numbers::contains)
.map(map1::get)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.