我正在开发一个程序来验证 map 是否包含某些值集。 Map
API 有一种称为 map.containsValue(string)
的方法。但是,此方法将完整的字符串验证为值。
import java.util.HashMap;
import java.util.Map;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(6, "P_T");
map.put(7, "P_Q_T");
map.put(8, "T");
map.put(9, "A");
map.put(10, "B");
map.put(11, "P_A");
map.put(1, "P_1");
map.put(2, "Q");
map.put(3, "P_Q");
map.put(4, "Q_T");
map.put(5, "T");
System.out.println("Map is = "+map);
System.out.println("Result is = " + map.containsValue("P"));
}
}
以上程序将返回输出为:
Map is = {1=P_1, 2=Q, 3=P_Q, 4=Q_T, 5=T, 6=P_T, 7=P_Q_T, 8=T, 9=A, 10=B, 11=P_A}
Result is = false
我的要求是 Result
应该为真,因为 Map 包含键 1、3、6、7、11,其中包含 char P
作为值。
我有一个解决方案,我可以使用循环来验证每个值,然后为 P
字符找到 indexOf
每个值。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(6, "P_T");
map.put(7, "P_Q_T");
map.put(8, "T");
map.put(9, "A");
map.put(10, "B");
map.put(11, "P_A");
map.put(1, "P_1");
map.put(2, "Q");
map.put(3, "P_Q");
map.put(4, "Q_T");
map.put(5, "T");
System.out.println("Map is = " + map);
System.out.println("Result is = " + map.containsValue("P"));
System.out.println("Result from loop is = " + verifyMap(map));
}
private static boolean verifyMap(Map<Integer, String> map) {
// TODO Auto-generated method stub
Set<Integer> set = map.keySet();
Iterator<Integer> itr = set.iterator();
while (itr.hasNext()) {
Integer integer = (Integer) itr.next();
String str = map.get(integer);
if (str.indexOf("P") >= 0)
return true;
}
return false;
}
}
我用 indexOf
方法而不是 contains
评估了 string
,后者稍微快一些。
这将返回所需的结果:
Result from loop is = true
但是,我只想知道,有没有其他方法可以验证?
最佳答案
您可以使用 Java 8 Streams 用更少的代码编写您的方法:
private static boolean verifyMap(Map<Integer, String> map) {
return map.values().stream().anyMatch(str->str.indexOf("P") >= 0);
}
即使在 Java 7 中,您的方法也可以更短:
private static boolean verifyMap(Map<Integer, String> map) {
for (String str : map.values()) {
if (str.indexOf("P") >= 0)
return true;
}
return false;
}
关于java - 如何用部分字符串验证 HashMap containsValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820524/