对于一些Java新手,想要知道一个map中的value是否包含某值,或者list中是否包含某值,可能会选择遍历,比如:
Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", '2');
map.put("3", true);
map.put("4", 1.4);
map.put("5", "no");
boolean isContainValue = false;
for (String s : map.keySet()) {
if (map.get(s).equals(1.4)) {
isContainValue = true;
break;
}
}
System.out.println(isContainValue);
或者:
List<Student> list = new ArrayList<>();
list.add(new Student("小明", 18));
list.add(new Student("小刚", 20));
list.add(new Student("小霞", 19));
list.add(new Student("小智", 21));
boolean isContainProperty = false;
for (Student student : list) {
if ("小明".equals(student.getName())) {
isContainProperty = true;
break;
}
}
System.out.println(isContainProperty);
但其实,可以这样:
boolean isContainValue = map.containsValue(1.4);
以及:
boolean isContainProperty = list.stream().anyMatch(o -> "小明".equals(o.getName()));
当然,这是存在,如要想要不存在或者任意,可以把anyMatch换成noneMatch或者allMatch。