【发布时间】:2017-07-26 09:55:11
【问题描述】:
Map<String, Integer> hm = new HashMap<>();
//assume hm is populated
if(hm.containValue(***){ ... }
// *** = contains even number
我尝试做类似(x -> x % 2 == 0) 的操作,但它不起作用。
有什么建议吗?
【问题讨论】:
Map<String, Integer> hm = new HashMap<>();
//assume hm is populated
if(hm.containValue(***){ ... }
// *** = contains even number
我尝试做类似(x -> x % 2 == 0) 的操作,但它不起作用。
有什么建议吗?
【问题讨论】:
假设我们有一个谓词:
Predicate<Integer> isEvenNumber = x -> x % 2 == 0;
检查 map 的值是否为偶数:
boolean containsEvenNumber = map.values().stream().anyMatch(isEvenNumber);
计算所有偶数:
long countEvenNumbers = map.values().stream().filter(isEvenNumber).count();
得到所有偶数
有一个列表:
List<Integer> evenNumbers = map.values().stream().filter(isEvenNumber).collect(Collectors.toList());
使用数组:
int[] evenNumbers = map.values().stream().filter(isEvenNumber).mapToInt(Integer::intValue).toArray();
【讨论】:
hm.values().stream().filter(x->x%2==0).count() > 1 我想是的 J
如果在地图的值中找到任何偶数,则以下代码为您提供布尔值 true,否则为 false。
public static void main(String[] args) {
// Initialize Map
Map<String, Integer> hm = new HashMap<String , Integer>(){{
put("A", 1);
put("B", 3);
put("C", 4);
put("D", 7);
}};
boolean foundEven = hm.values()
.stream()
.anyMatch(i -> i % 2 == 0);
System.out.println(foundEven);
}
【讨论】:
我认为您应该手动循环检查每个值:
for (int i : hm.values()) {
if( i % 2 == 0) {
//do what you want here
}
}
【讨论】: